Este objeto es un tipo integral. ¿Puedo obtener su valor en menos de cinco líneas de código?

StackOverflow https://stackoverflow.com/questions/631994

  •  08-07-2019
  •  | 
  •  

Pregunta

Tengo un lector de datos. Quiero comparar su valor con el valor 42. Sé que es un tipo integral (por ejemplo, lo que MySQL llama INT , TINYINT , SMALLINT , MEDIUMINT , BIGINT , JUMBODELUXEINT , etc.). No quiero conectar el tipo real al código C #. Lo mejor que se me ocurrió es

object x = reader.GetValue(i);
uint k = x is byte ? (byte) x
    : x is short ? (uint) (short) x
    : x is ushort ? (ushort) x
    : x is int ? (int) (int) x
    : (uint) x;
if (k == 42) { ... }

Esto parece increíblemente largo. Intenté usar Equals pero diferentes tipos integrales con el mismo valor no parecen probar como iguales.

¿Hay una mejor manera?

¿Fue útil?

Solución

Simplemente verificando Convert.ToUInt32 (objeto) ... sí, funciona bien:

using System;

class Test
{
    static void Main()
    {
        Check((byte)10);
        Check((short)10);
        Check((ushort)10);
        Check((int)10);
        Check((uint)10);
    }

    static void Check(object o)
    {
        Console.WriteLine("Type {0} converted to UInt32: {1}",
                          o.GetType().Name, Convert.ToUInt32(o));
    }
}

En otras palabras, su código puede ser:

object x = reader.GetValue(i);
uint k = Convert.ToUInt32(x);
if (k == 42) { ... }

Alternativamente, dado que todos los uint son representables como largos, si está utilizando un lector de datos, ¿podría intentar con reader.GetInt64 (i) ? No sé de antemano si la conversión se realizará por usted, pero probablemente valga la pena intentarlo.

Otros consejos

if(Convert.ToUInt32(reader.GetValue(i)) == 42) { ... }

También podría hacer las respuestas de Skeet y Daniel a la inversa de esta manera:

if (k == Convert.ChangeType(42, k.GetType()) { ... }

Sin embargo, no lo he probado.

No estoy seguro si te entiendo correctamente, pero creo que esto debería funcionar:

int x = int.Parse(reader.GetValue(i).ToString());
if(x == 42) { // do your logic }

Puedes probar esto:

unit k = Convert.ToUInt32(x);

Sin embargo, sería mejor cambiar el nombre de sus variables. Las variables de 1 letra son tan la semana pasada .

Esto debería funcionar:

object x = reader.GetValue(i);

uint k;
try
{
    k = Convert.ToUInt32(x);
}
catch(InvalidCastException e) { ... }
if (k == 42) { ... }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top