VB.NET是否会“ If”?操作员原因拳击? [英] Does the VB.NET "If" operator cause boxing?

查看:79
本文介绍了VB.NET是否会“ If”?操作员原因拳击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在VB / VB.NET中工作过的人看到了类似于以下可恶的代码:

Those of us who've worked in VB/VB.NET have seen code similar to this abomination:

Dim name As String = IIf(obj Is Nothing, "", obj.Name)

我说憎恶出于以下三个简单原因:

I say "abomination" for three simple reasons:


  1. IIf 函数,评估所有参数;因此,如果在上述调用中 obj 无效,则会抛出 NullReferenceException 。对于习惯于使用C#之类的短路三元运算符的人来说,这是意外的行为。

  2. 因为 IIf 是一个函数,因此会导致函数调用的开销。再说一次,尽管这没什么大不了的,但是对于期望它表现为语言固有的三元运算的人来说,感觉并不对。

  3. IIf 是非泛型的,因此接受 Object 类型的参数,这意味着以下调用框(我相信)三个整数:

  1. IIf is a function, all of whose parameters are evaluated; hence if obj is nothing in the above call then a NullReferenceException will be thrown. This is unexpected behavior for someone who's accustomed to short-circuited ternary operators in languages like C#.
  2. Because IIf is a function, it thus incurs the overhead of a function call. Again, though this isn't a big deal, it just doesn't feel right to someone who expects for it to behave as a ternary operation intrinsic to the language.
  3. IIf is non-generic and therefore accepts parameters of type Object, which means the following call boxes (I believe) a total of three integers:

'框的第二个和第三个参数以及返回值'

Dim值作为整数= IIf(condition,1,-1)

现在,在较新的VB.NET版本中(我不确定数字是多少),引入了 If 运算符,该运算符可以正常工作 IIf 函数的方式相同,但是(据我所知)没有相同的缺点。也就是说,它确实提供短路,并且一种固有的VB操作。但是,我不确定最后一部分。 MSDN文档似乎并未表明 If 是否装上其参数。有人知道吗?

Now, in some more recent version of VB.NET (I'm not sure what the number is), the If operator was introduced, which works exactly the same way as the IIf function but (as I understand it) without the same shortcomings. That is to say, it does provide short-circuiting and it is an intrinstic VB operation. However, I'm not sure about the last part. The MSDN documentation doesn't seem to indicate whether If boxes its arguments or not. Does anyone know?

推荐答案

主要是您正确识别了新的 If 作为 operator 而不是函数。它也是类型安全的,因此不需要装箱,并且是直接映射到条件/三元/吗? C / C ++ / C#/ Java / etc中的运算符

The main thing is that you correctly identified the new If as an operator rather than a function. It is also typesafe and therefore does not need boxing, and is a direct mapping to the conditional/ternary/? operator in C/C++/C#/Java/etc

即使没有新的运算符,也可以使用以下代码对VB.Net进行一些改进:

Even without the new operator, you can get some improvement in VB.Net with this code:

Public Shared Function IIf(Of T)(ByVal Expression As Boolean, ByVal TruePart As T, ByVal FalsePart As T) As T
    If Expression Then Return TruePart Else Return FalsePart
End Function

这篇关于VB.NET是否会“ If”?操作员原因拳击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆