Nullable的诡异之处……

原来Nullable type是null的时候,以它作为被调用对象是不会得到NullReferenceException的。以前都没发现,得小心点才行……

引用Steve Wellens在CodeProject上发表的[url=http://www.codeproject.com/script/Articles/BlogArticle.aspx?aid=34720]C# Nullable Types…Subtlety[/url],
 int Test1 = 0;  // standard value type
int? Test2 = null; // nullable value type
Object Test3 = null; // reference type

Response.Write("Test1: " + Test1.ToString() + "<br />");
Response.Write("Test2: " + Test2.ToString() + "<br />");
//Response.Write("Test3: " + Test3.ToString() + "<br />");

// Output:
//
// Test1: 0 // correct
// Test2: // no exception, what? but it's null!
//
// If Test3 is allowed to run, we get:
// "Object reference not set to an instance of an object."

(他这段代码是在ASP.NET里测试的,所以是用Response.Write())

[color=red]更新:
参照下面的回复:Nullable<T>是值类型,自身不会为null。使执行int? Test2 = null;之后,Test2指向的是一个代表null的Nullable<int>的实例,所以后面自然不会有异常。[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值