2011-05-08 88 views
4

假設v是空的,我不知道會造成什麼影響/這些用法之間的差異:正確的方式,如果有可爲空值

VB:

  1. 如果v沒什麼然後
  2. 如果v.HasValue然後

C#:

  1. 如果(V == NULL)
  2. 如果(!v.HasValue)
+0

@BoltClock,你鏈接到的問題是一個C#問題。從代碼來看,這個問題是關於VB.NET的。這兩種語言圍繞可空類型確實有不同的皺紋,所以我不會稱這是重複的。 – 2011-05-08 07:30:52

+1

@Joe White:永遠不會知道 - 謝謝你指出。應該zap我的自動鏈接評論... – BoltClock 2011-05-08 07:31:57

回答

4

沒有區別 - 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()

0

使用HasValue財產

If v.HasValue Then 
    ... 
End 
+2

你能證明你的答案? – empi 2011-05-08 07:31:01

3

沒有區別。你總是得到相同的結果。 前段時間我寫了幾個單元測試,檢查可空類型的不同行爲:http://www.copypastecode.com/67786/

+0

鏈接已損壞。 – djv 2015-04-15 17:01:10

1

絕對沒有差別。這只是你的風格偏好。

的代碼,這兩個行會產生完全相同的IL代碼:

if (!v.HasValue) 

if (v == null) 

可以在IL代碼,在這兩種情況下可空:: get_HasValue()被調用。

對不起,我在C#中做了樣本,而不是VB。