例如,当我有一个可以为空的长度时,它们之间是否有任何区别
myNullableLong.HasValue
Run Code Online (Sandbox Code Playgroud)
和
myNullableLong != null
Run Code Online (Sandbox Code Playgroud)
......还是只是'语法糖'?
Jon*_*eet 56
这只是语法糖.它们的行为方式完全相同 - 无效测试实际上被编译成一个调用HasValue
.
样品:
public class Test
{
static void Main()
{
int? x = 0;
bool y = x.HasValue;
bool z = x != null;
}
}
Run Code Online (Sandbox Code Playgroud)
IL:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 25 (0x19)
.maxstack 2
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: call instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)
IL_0008: ldloca.s V_0
IL_000a: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_000f: pop
IL_0010: ldloca.s V_0
IL_0012: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_0017: pop
IL_0018: ret
} // end of method Test::Main
Run Code Online (Sandbox Code Playgroud)
这是语法糖; Nullable<T>
实际上是一个struct
,所以它实际上不可能null
; 编译器将与之比较的调用null
(如第二个示例)转换为调用HasValue
.
但请注意,将a Nullable<T>
装入一个object
将导致T
(如果它有值)或null
(如果没有)的值.
IE
int? foo = 10; // Nullable<int> with a value of 10 and HasValue = true
int? bar = null; // Nullable<int> with a value of 0 and HasValue = false
object fooObj = foo; // boxes the int 10
object barObj = bar; // boxes null
Console.WriteLine(fooObj.GetType()) // System.Int32
Console.WriteLine(barObj.GetType()) // NullReferenceException
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7873 次 |
最近记录: |