好吧,这个问题可能看起来很奇怪。确实如此。
然而,我坚信这些技巧有助于理解语言和 .net 平台。
C# 编译器如何处理可空类型暗示了这个问题。
Nullable<T>
是一个结构。但是编译器不是这个结构而是它持有的值或者只是空引用。
在盒装 Nullable 的情况下,拆箱将如何工作也很有趣。
Nullable<int> myInt = boxedStruct as Nullable<int>;
我的意思boxedStruct
是,这不是一个装箱的 int,而是整个结构。
好吧,可能是在 CLR 级别对 Nullables 进行了不同的处理,因为我无法理解下面程序的输出。
class Program
{
public static bool? Property { get; set; }
static void Main(string[] args)
{
Property = true;
var valueType = typeof (Program).GetProperty("Property").GetValue(null).GetType();
var propType = typeof (Program).GetProperty("Property").PropertyType;
Console.WriteLine("Value's type '{0}' is the same as type of the property '{1}' - '{2}'", valueType, propType, valueType == propType);
Console.ReadKey();
}
}
输出:
值的类型“System.Boolean”与属性“System.Nullable`1[System.Boolean]”的类型相同 - “False”
更新:
这里有什么规范(ECMA 335)说:
I.8.2.4 值的装箱和拆箱
...
如果值类型是可为空的类型——定义为值类型 System.Nullable 的实例化——结果是空引用或其类型 T 的 Value 属性的按位副本,取决于其 HasValue 属性(分别为 false 和 true)。
所以如果我理解正确的话。Nullable<T>
strcut 不能在 .Net Framework 中装箱,不仅 C# 编译器不可能,CLR 也是如此。