无法将对象转换为短整型

3

我遇到了一个问题,将对象转换为短整型无法正常工作。

在一个类中,我有以下内容(仅供参考):

public const uint message_ID = 110;

另一个类中,在构造函数中,我有以下代码:

Assembly asm = Assembly.GetAssembly(typeof(ProtocolTypeManager));

foreach (Type type in asm.GetTypes())
{
      if (type.Namespace == null || !type.Namespace.StartsWith(typeof(MyClass).Namespace))
                continue;

      FieldInfo field = type.GetField("message_ID");

      if (field != null)
      {
           short id = (short)(field.GetValue(type));
           ...
      }
}

在转换之前,我的程序一切正常。我的字段不是空的,而且field.GetValue(type)返回了正确的对象(即value = 110)。

我曾经看到过一个地方说,从object到int的拆箱是可以的,但是我尝试了一下,仍然不行:

object id_object = field.GetValue(type);
int id_int = (int)id_object;
short id = (short)id_object;

这个异常是这样的: http://puu.sh/5d2jR.png(抱歉是法语,它说明这是一种类型或强制转换错误)。
有没有人有解决方案?
谢谢, Veriditas。
2个回答

5

您需要将其转换为uintmessage_ID的原始类型):

object id_object = field.GetValue(type);
uint id_uint = (uint)id_object;
short id = (short)id_uint;

在这里,您可以找到一篇关于此主题的非常好的阅读材料:表示和身份


好的,我刚试了一下。第一个转换,从对象到无符号整数可以工作,但第二个不行。在更正时,我意识到了自己的愚蠢。这样可以工作: object id_object = field.GetValue(type); uint id_uint = (uint)id_object; short id = (short)id_uint;第二次转换涉及到id_uint而不是id_object...非常感谢你,Alberto :) - Veriditas
2
第二个转换应该是 short id = (short)id_uint; 你也可以缩短为 short id = (short)(uint)id_object; - Rory McCrossan
1
有效地,Rory,这更短。谢谢! - Veriditas

0

上面的解决方案对我不起作用,我用以下方法解决:

short value1 = Convert.ToInt16(data1["Variable"].ToString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接