在VB.NET中,C#的`default`等价于什么? [英] What is the equivalent of C#'s `default` in VB.NET?
问题描述
我通常在C#中使用C#,我正在考虑一些VB.NET代码中的性能问题 - 我想能够比较某种类型的默认值(类似于C#的 default
关键字)。
I'm normally at home in C#, and I'm looking at a performance issue in some VB.NET code -- I want to be able to compare something to the default value for a type (kind of like C#'s default
keyword).
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 在语义上是相同的,但是如果我这样做的话:
I was led to believe that Nothing
was semantically the same, yet if I do:
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
被评估。但是,如果我这样做:
$ b
Then when T2
is Integer
, and the value of id
is 0
, the condition still passes, and the body of the if
is evaluated. However if I do:
Public Function Bar( id As Integer ) As T1
If id <> Nothing Then
' ...
End If
End Function
然后条件不符合,并且不评估正文...
Then the condition is not met, and the body is not evaluated...
推荐答案
这不是一个完整的解决方案,因为你原来的C#代码不能编译。您可以通过局部变量使用Nothing:
This is not a complete solution, as your original C# code doesn't compile. You can use Nothing via a local variable:
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#版本不编译一样 - 你可以比较不受约束的类型参数的值。
That doesn't compile, in the same way that the C# version doesn't compile - you can't compare values of unconstrained type parameters like that.
可以使用 EqualityComparer(Of T)
- 但那么你甚至不需要局部变量:
You can use EqualityComparer(Of T)
though - and then you don't even need the local variable:
If Not EqualityComparer(Of T).Default.Equals(id, Nothing) Then
这篇关于在VB.NET中,C#的`default`等价于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!