VB.NET中的C#的“default”是什么?

前端之家收集整理的这篇文章主要介绍了VB.NET中的C#的“default”是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通常在C#中回家,我正在看一些VB.NET代码中的性能问题 – 我想能够比较一些类型的类型(类似于C#的默认关键字)的默认值。
  1. public class GenericThing<T1,T2>
  2. {
  3. public T1 Foo( T2 id )
  4. {
  5. if( id != default(T2) ) // There doesn't appear to be an equivalent in VB.NET for this(?)
  6. {
  7. // ...
  8. }
  9. }
  10. }

我被带领相信Nothing在语义上是一样的,但如果我这样做:

  1. Public Class GenericThing(Of T1,T2)
  2. Public Function Foo( id As T2 ) As T1
  3. If id IsNot Nothing Then
  4. ' ...
  5. End If
  6. End Function
  7. End Class

那么当T2是整数,并且id的值为0时,条件仍然通过,并且if的主体被评估。但是,如果我这样做:

  1. Public Function Bar( id As Integer ) As T1
  2. If id <> Nothing Then
  3. ' ...
  4. End If
  5. End Function

然后条件不符合,身体没有评估…

这不是一个完整的解决方案,因为您的原始C#代码不能编译。您可以通过局部变量使用Nothing:
  1. Public Class GenericThing(Of T)
  2. Public Sub Foo(id As T)
  3. Dim defaultValue As T = Nothing
  4. If id <> defaultValue Then
  5. Console.WriteLine("Not default")
  6. Else
  7. Console.WriteLine("Default")
  8. End If
  9. End Function
  10. End Class

这不能编译,就像C#版本不能编译一样 – 你无法比较像这样的无约束类型参数的值。

您可以使用EqualityComparer(Of T) – 然后您甚至不需要本地变量:

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

猜你在找的VB相关文章