Is there a conditional ternary operator in VB.NET?

吃可爱长大的小学妹 提交于 2019-11-26 00:15:30

问题


In Perl (and other languages) a conditional ternary operator can be expressed like this:

my $foo = $bar == $buz ? $cat : $dog;

Is there a similar operator in VB.NET?


回答1:


Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

Dim foo as String = If(bar = buz, cat, dog)

[EDIT]

Prior to 2008 it was "IIf", which worked almost identically to the If operator described Above.

Example:

Dim foo as String = IIf(bar = buz, cat, dog)



回答2:


iif has always been available in VB, even in VB6.

Dim foo as String = iif(bar = buz, cat, dog)

It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.




回答3:


If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

For example, if your not careful you may be tempted to try something like:

Dim foo As Integer? = If( someTrueExpression, Nothing, 2)

Will give "foo" a value of 0!

I think the '?' operator equivalent in C# would instead fail compilation



来源:https://stackoverflow.com/questions/576431/is-there-a-conditional-ternary-operator-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!