gpt4 book ai didi

c# - 不可能从物体转换到短

转载 作者:行者123 更新时间:2023-11-30 14:58:02 25 4
gpt4 key购买 nike

我遇到了一个问题。从 object 到 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));
...
}
}

在类型转换之前我没有问题。我的字段不为空,field.GetValue(type) 给我好对象(对象值 = 110)。

在某处,我读到从 object 到 int 的拆箱工作,好吧,我试过了,但它仍然不起作用:

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

异常(exception)是这个:http://puu.sh/5d2jR.png (对不起法语。它说这是类型或转换错误)。

有没有人有解决办法?

谢谢,真实。

最佳答案

您需要将其拆箱为uint(message_ID 的原始类型):

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

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

关于c# - 不可能从物体转换到短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com