.Net - Cast or convert a boxed byte?, short? or int? to int?

江枫思渺然 提交于 2019-12-11 14:01:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!