我想知道下面两个语句之间的区别:
Causes a NullReferenceException - it is OK.
object test1 = default(int?); object result = test1.ToString();
Returns an empty string "", why?
object test2 = default(int?).ToString();
This is same as 2.
int? test3 = null; if (test3.ToString() == string.Empty) //returns true { Console.WriteLine("int? = String.Empty, isn't it strange?"). }
And just for fun - I can prove that bool can be equal to int value (hmmm how? bool can be only false, or true and int never can be that).
if (default(int?).ToString() == default(bool?).ToString()) //returns true because both are empty strings { Console.WriteLine("int = bool"); }
注意: default(int?) 返回 null。
Nullable<T>
是一个值类型,实际上不能为null
。它只是以一种编程方式编写,使得与null
的比较在HasValue
属性为false
时返回 true。(将其设置为null
将会将HasValue
属性设置为false
) - dialerToString()
的默认(int?)上调用GetType()
。装箱可能有点棘手。 - Dan Bryant