Dot-Net

VB.NET 中 C# 的 default 的等價物是什麼?

  • January 20, 2011

我通常在家中使用 C#,並且正在研究一些 VB.NET 程式碼中的性能問題——我希望能夠將某些內容與類型的預設值進行比較(有點像 C# 的default關鍵字)。

public class GenericThing<T1, T2>
{
   public T1 Foo( T2 id )
   {
       if( id != default(T2) ) // There doesn't appear to be an equivalent in VB.NET for this(?)
       {
           // ...
       }
   }
}

我被引導相信這Nothing在語義上是相同的,但如果我這樣做:

Public Class GenericThing(Of T1, T2)
   Public Function Foo( id As T2 ) As T1
       If id IsNot Nothing Then
           ' ...
       End If
   End Function
End Class

然後當T2isInteger和 is 的值時id0條件仍然通過,並且if評估 the 的主體。但是,如果我這樣做:

   Public Function Bar( id As Integer ) As T1
       If id <> Nothing Then
           ' ...
       End If
   End Function

然後條件不滿足,body不求值……

這不是一個完整的解決方案,因為您的原始 C# 程式碼無法編譯。您可以通過局部變數使用 Nothing:

Public Class GenericThing(Of T)
   Public Sub Foo(id As T)
       Dim defaultValue As T = Nothing
       If id <> defaultValue Then
           Console.WriteLine("Not default")
       Else
           Console.WriteLine("Default")
       End If
   End Function
End Class

這不能編譯,就像 C# 版本不能編譯一樣——你不能像這樣比較不受約束的類型參數的值。

你可以使用EqualityComparer(Of T)- 然後你甚至不需要局部變數:

If Not EqualityComparer(Of T).Default.Equals(id, Nothing) Then

與 C# 不同,VB.NET 不需要用表達式初始化局部變數。它由執行時初始化為其預設值。正是您需要替代預設關鍵字的東西:

   Dim def As T2    '' Get the default value for T2
   If id.Equals(def) Then
      '' etc...
   End If

不要忘記評論,它會讓某人“嗯?” 一年後。

引用自:https://stackoverflow.com/questions/4750152