假设 v 可以为空,我想知道这些用法之间的含义/区别是什么:
VB:
- 如果 v 什么都不是
- If v.HasValue Then
C#:
- 如果(v == null)
- if (!v.HasValue)
最佳答案
没有区别 - Is Nothing
被编译为使用 HasValue
。例如这个程序:
Public Class Test
Public Shared Sub Main()
Dim x As Nullable(Of Integer) = Nothing
Console.WriteLine(x Is Nothing)
End Sub
End Class
转换为这个 IL:
.method public static void Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// Code size 24 (0x18)
.maxstack 2
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0008: ldloca.s V_0
IL_000a: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_000f: ldc.i4.0
IL_0010: ceq
IL_0012: call void [mscorlib]System.Console::WriteLine(bool)
IL_0017: ret
} // end of method Test::Main
注意对 get_HasValue()
的调用。
关于c# - 检查 nullable 是否有值的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926184/