سؤال

I'm facing a problem. A cast from object to short doesn't work.

In a class I have that (juste an exemple) :

public const uint message_ID = 110;

And in another class, in the constructor, I have that :

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));
           ...
      }
}

I have no problem untill the cast. My field isn't null and field.GetValue(type) give me the good object (object value = 110).

Somewhere, I read that the unboxing from object to int work, well, I tried it, but it still doesn't work :

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

The exception is this one : http://puu.sh/5d2jR.png (sorry for the French. It says that it's a type or cast error).

Is there anyone who have the solution ?

Thank you, Veriditas.

هل كانت مفيدة؟

المحلول

You need to unbox it to uint (the original type of message_ID):

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

Here you can find a very good read about this topic: Representation and Identity

نصائح أخرى

The solution above is not working for me, I solved with this:

short value1 = Convert.ToInt16(data1["Variable"].ToString());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top