原来Nullable type是null的时候,以它作为被调用对象是不会得到NullReferenceException的。以前都没发现,得小心点才行……
引用Steve Wellens在CodeProject上发表的[url=http://www.codeproject.com/script/Articles/BlogArticle.aspx?aid=34720]C# Nullable Types…Subtlety[/url],
(他这段代码是在ASP.NET里测试的,所以是用Response.Write())
[color=red]更新:
参照下面的回复:Nullable<T>是值类型,自身不会为null。使执行int? Test2 = null;之后,Test2指向的是一个代表null的Nullable<int>的实例,所以后面自然不会有异常。[/color]
引用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]