在VB.NET中,C#的`default`等价于什么?

编程入门 行业动态 更新时间:2024-10-24 10:19:25
本文介绍了在VB.NET中,C#的`default`等价于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我通常在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`等价于什么?

本文发布于:2023-11-09 15:38:38,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:VB   NET   default

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!