VB.NET 中是否有条件三元运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/576431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a conditional ternary operator in VB.NET?
提问by Jim Counts
In Perl (and other languages) a conditional ternary operator can be expressed like this:
在 Perl(和其他语言)中,条件三元运算符可以这样表示:
my $foo = $bar == $buz ? $cat : $dog;
Is there a similar operator in VB.NET?
VB.NET 中是否有类似的运算符?
回答by Beep beep
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
取决于版本。在If
2008年VB.NET运算符是一个三元操作(以及空聚结操作者)。这是刚刚推出的,在 2008 年之前这是不可用的。以下是更多信息: Visual Basic If 公告
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.
在 2008 年之前,它是IIf
,其工作方式与上述If
操作员几乎相同。
Example:
例子:
Dim foo as String = IIf(bar = buz, cat, dog)
回答by Kris Erickson
iif has always been available in VB, even in VB6.
iif 在 VB 中一直可用,甚至在 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.
因此,它不是真正的运算符,而是 Microsoft.VisualBasic 命名空间中的函数。
回答by unnknown
If() is the closest equivalent but bewareof implicit conversions going on if you have set "Option Strict off"
If() 是最接近的等价物,但如果您设置了“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!
会给“foo”一个值为 0!
I think the '?' operator equivalent in C# would instead fail compilation
我觉得 '?' C# 中的等价运算符会导致编译失败