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