繁体   English   中英

VB.NET中C#的`default`相当于什么?

[英]What is the equivalent of C#'s `default` in VB.NET?

我通常在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

然后当T2Integerid值为0 ,条件仍然通过,并且if的主体被计算。 但是,如果我这样做:

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

然后不满足条件,并且不评估身体......

与C#不同,VB.NET不需要使用表达式初始化局部变量。 它由运行时初始化为其默认值。 正是您需要的替代默认关键字:

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

不要忘记评论,它会让某人去'嗯?' 一年后。

这不是一个完整的解决方案,因为您的原始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

您的代码中的问题是IsNot运算符,而不是Nothing关键字。 来自文档

IsNot运算符确定两个对象引用是否引用不同的对象。 但是,它不执行值比较。

您正尝试与参考运算符进行值比较。 一旦你意识到这一点,Jon Skeet或Hans Passant的答案将成为明显的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM