VB.NET中的C#的“default”是什么?
发布时间:2020-12-17 00:01:07 所属栏目:大数据 来源:网络整理
导读:我通常在C#中回家,我正在看一些VB.NET代码中的性能问题 – 我想能够比较一些类型的类型(类似于C#的默认关键字)的默认值。 public class GenericThingT1,T2{ public T1 Foo( T2 id ) { if( id != default(T2) ) // There doesn't appear to be an equivalent
|
我通常在C#中回家,我正在看一些VB.NET代码中的性能问题 – 我想能够比较一些类型的类型(类似于C#的默认关键字)的默认值。
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
那么当T2是整数,并且id的值为0时,条件仍然通过,并且if的主体被评估。但是,如果我这样做: Public Function Bar( id As Integer ) As T1
If id <> Nothing Then
' ...
End If
End Function
然后条件不符合,身体没有评估…
这不是一个完整的解决方案,因为您的原始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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
