Unboxing object containing a value which is known to be assignable to an integer variable
If I have an object
instance and I know it is actually a boxed integer, then I can simply cast it back to int like this:
object o = GetSomethingByName("foo");
int i = (int)o;
However, I don't actually know that the value is an integer. I only know that it can be assigned to an integer. For example, it could be a byte
, and the above code would throw InvalidCastException
in that case. I开发者_Go百科nstead I would have to do this:
object o = GetSomethingByName("foo");
int i = (int)(byte)o;
The value could also be a short
, or something else which can be assigned to an int
. How do I generalize my code to handle all those cases (without handling each possibility separately)?
Simply writing the question made me remember that there is a Convert
class. This seems to work:
int i = Convert.ToInt32(o);
edit: but unfortunately, it will also do type conversions that I actually don't want, like parsing strings.
It is interesting to see how Convert.ToInt32
accomplishes the conversion:
public static int ToInt32(object value)
{
return value == null? 0: ((IConvertible)value).ToInt32(null);
}
The trick is to cast the object to IConvertible
.
精彩评论