2013-11-09 13 views
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。

回答

5

你需要把它拆箱到uint(原始類型的message_ID):

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

在這裏你可以找到一個很好的閱讀關於這個話題:Representation and Identity

+0

好吧,我剛剛試了一下。第一個演員,從對象到非工作,第二個不是。而且,在糾正的同時,我意識到我所做的愚蠢。這項工作: object id_object = field.GetValue(type); uint id_uint =(uint)id_object; short id =(short)id_uint; 第二個演員關注的是id_uint,不要id_object ...非常感謝你Alberto :) – Veriditas

+2

第二個演員應該是'short id =(short)id_uint;'你也可以縮短爲'short id =(short )(uint)id_object;' –

+1

有效Rory,它更短。謝謝 ! – Veriditas