2013-11-09 1 views
3

문제가 있습니다. 개체에서 단편으로 캐스트가 작동하지 않습니다. 것을 개체에서 짧은 문자로 불가능한 캐스트

public const uint message_ID = 110; 

그리고 다른 클래스에서

, 생성자에서, 내가 가진 : 나는 (AN exemple를 juste) 것을이 클래스에서

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 (type)이 좋은 객체 (객체 값 = 110)를 제공합니다. 프랑스에 대한 http://puu.sh/5d2jR.png (죄송합니다 :

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

예외이 하나입니다

어딘가에, 내가 아니라, 내가 그것을 시도,하지만 여전히 작동하지 않습니다, 객체의 언 박싱 일을 int로 읽어 보시기 바랍니다 그것은 형식 또는 형변환 오류라고합니다).

해결책이있는 사람이 있습니까?

고맙습니다. 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

좋아, 난 그냥 그것을 시도. 객체에서 객체로의 첫 번째 캐스트는 두 번째로 수행되지 않습니다. 그리고 정정하는 동안, 나는 내가 한 어리 석음을 깨닫는다. 이 작품 : 개체 id_object = field.GetValue (유형); uint id_uint = (단위) id_object; 짧은 ID = (짧은) id_uint; 두 번째 캐스팅 id_uint와 id_object ... do not not alberto :) – Veriditas

+2

두 번째 캐스팅은'short id = (short) id_uint; '여야합니다'short id = (short) (uint) id_object; ' –

+1

로리, 효과적입니다. 고맙습니다 ! – Veriditas