从物体到短的不可能

时间:2013-11-09 10:59:06

标签: c# object types casting short

我遇到了问题。从对象到短的转换不起作用。

在课堂上我有(例如,一个例子):

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

我没有问题直到演员阵容。我的字段不是null而field.GetValue(type)给我一个好的对象(对象值= 110)。

在某个地方,我读到从对象到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 个答案:

答案 0 :(得分:5)

您需要将其解包到uint(原始类型message_ID):

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

在这里,您可以找到关于此主题的非常好的阅读:Representation and Identity

答案 1 :(得分:0)

上面的解决方案对我不起作用,我用这个解决了:

short value1 = Convert.ToInt16(data1["Variable"].ToString());
相关问题