代码之家  ›  专栏  ›  技术社区  ›  pdc

此对象是整型对象。我能在少于五行的代码中得到它的值吗?

  •  4
  • pdc  · 技术社区  · 17 年前

    我有一个数据阅读器。我想将其中的值与值42进行比较。我知道它是一个整数类型(例如,MySQL所调用的 INT , TINYINT , SMALLINT , MEDIUMINT , BIGINT , JUMBODELUXEINT

    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) { ... }
    

    Equals 但具有相同值的不同积分类型的测试结果并不相同。

    有更好的办法吗?

    6 回复  |  直到 17 年前
        1
  •  9
  •   Jon Skeet    17 年前

    只是检查一下 Convert.ToUInt32(object)

    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));
        }
    }
    

    换句话说,您的代码可以是:

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

    或者,考虑到这一切 uint reader.GetInt64(i) ? 我不知道转换是否会为您完成,但可能值得一试。

        2
  •  6
  •   Daniel LeCheminant    17 年前
    if(Convert.ToUInt32(reader.GetValue(i)) == 42) { ... }
    
        3
  •  2
  •   Mykroft    17 年前

    你也可以做双向飞碟和丹尼尔的回答,像这样:

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

        4
  •  0
  •   Ahmed    17 年前

    我不确定我是否理解正确,但我认为这应该有效:

    int x = int.Parse(reader.GetValue(i).ToString());
    if(x == 42) { // do your logic }
    
        5
  •  0
  •   Michael Meadows    17 年前

    unit k = Convert.ToUInt32(x);
    

    不过,重命名变量会更好。1字母变量为 苏欧上周 .

        6
  •  0
  •   Reed Copsey    17 年前

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