Ver*_*tas 3 c# types casting object short
我遇到了问题.从对象到短的转换不起作用.
在课堂上我有(juste an exemple):
public const uint message_ID = 110;
Run Code Online (Sandbox Code Playgroud)
在另一个类中,在构造函数中,我有:
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));
...
}
}
Run Code Online (Sandbox Code Playgroud)
我没有问题直到演员阵容.我的字段不是null,而field.GetValue(type)给了我好的对象(对象值= 110).
在某个地方,我读到从对象到int工作的拆箱,好吧,我试过了,但它仍然不起作用:
object id_object = field.GetValue(type);
int id_int = (int)id_object;
short id = (short)id_object;
Run Code Online (Sandbox Code Playgroud)
唯一的例外是这个:http://puu.sh/5d2jR.png(对不起法语.它说它是类型或强制转换错误).
有没有人有解决方案?
谢谢你,Veriditas.
您需要将其拆箱uint
(原始类型message_ID
):
object id_object = field.GetValue(type);
uint id_uint = (uint)id_object;
short id = (short)id_uint;
Run Code Online (Sandbox Code Playgroud)
在这里,您可以找到关于此主题的非常好的读物:表示和身份