问题
If I have an object
reference that references a byte?
, short?
or int?
, is there a way to unconditionally cast or convert that object reference to int? without writing separate code for each case?
For example:
byte? aByte = 42; // .. or aByte = null
object anObject = aByte;
//...
var anInt = (int?)anObject //As expected, doesn't work
回答1:
I'd use Convert.ToInt32(object):
object o = ...; // Boxing...
int? x = o == null ? (int?) null : Convert.ToInt32(o);
Note that when you box an int?
, short?
or byte?
, you always end up with a null reference or a boxed non-nullable value - there's no such thing as a "boxed nullable value" as such.
Convert.ToInt32
will work for all the boxed types you've mentioned - although it would also work for things like a string "42" etc. Is that a problem?
回答2:
var i = (anObject as IConvertible).ToInt32(null);
来源:https://stackoverflow.com/questions/7908101/net-cast-or-convert-a-boxed-byte-short-or-int-to-int