净 - 投或转换装箱字节?,短?或INT?为int? [英] .Net - Cast or convert a boxed byte?, short? or int? to int?

查看:143
本文介绍了净 - 投或转换装箱字节?,短?或INT?为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象引用,引用字节?短?诠释?,有没有办法无条件地投或转换的对象引用为int?无需编写单独的code每个案例?

例如:

 字节? aByte = 42; // ..或aByte = NULL
object对象= aByte;
// ...
VAR ANINT =(INT?)anObject //正如预期的那样,无法正常工作
 

解决方案

我会使用<一个href="http://msdn.microsoft.com/en-us/library/23511zys.aspx"><$c$c>Convert.ToInt32(object):

 对象o = ...; // 拳击...
诠释? X = O == NULL? (INT?)空:Convert.ToInt32(O);
 

请注意,当你框中诠释?短?字节?,你总是结束了一个空引用或盒装不可为空值 - 有没有这样的东西作为一个盒装空值这样

Convert.ToInt32 将适用于所有你所提到的盒装类型 - 尽管它会的的东西像一个字符串作品42 等那是一个问题吗?

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

解决方案

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?

这篇关于净 - 投或转换装箱字节?,短?或INT?为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆