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));
...
}
}
我直到剧组没问题。我的领域不是null和field.GetValue(类型)给我的好对象(对象值= 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。
好吧,我刚刚试了一下。第一个演员,从对象到非工作,第二个不是。而且,在纠正的同时,我意识到我所做的愚蠢。这项工作: object id_object = field.GetValue(type); uint id_uint =(uint)id_object; short id =(short)id_uint; 第二个演员关注的是id_uint,不要id_object ...非常感谢你Alberto :) – Veriditas
第二个演员应该是'short id =(short)id_uint;'你也可以缩短为'short id =(short )(uint)id_object;' –
有效Rory,它更短。谢谢 ! – Veriditas