如果 VB.NET (IIf) 的条件不等于 C# (?:) [英] If Condition of VB.NET (IIf) is not equal by C# (?:)
问题描述
VB 中的IIf 函数.NET:
IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
完全不等于 C# 条件运算符 (?:):
condition ? first_expression : second_expression;
当我将一些代码从 c# 转换为 vb.net 时,我知道转换后的代码无法正常工作,因为在 vb.net 中,如果条件在检查条件之前评估了真假部分!
When I convert some codes from c# to vb.net, I understand that converted codes not work correctly because in vb.net if conditional are evaluated both of the true and false parts before the condition is checked!
例如,C#:
public int Divide(int number, int divisor)
{
var result = (divisor == 0)
? AlertDivideByZeroException()
: number / divisor;
return result;
}
VB.NET:
Public Function Divide(number As Int32, divisor As Int32) As Int32
Dim result = IIf(divisor = 0, _
AlertDivideByZeroException(), _
number / divisor)
Return result
End Function
现在,我的 c# 代码成功执行,但每次 divisor
不等于零时,vb.net 代码都会运行 AlertDivideByZeroException()
和 number/除数
.
Now, my c# codes executed successfully but vb.net codes every times that divisor
is not equal by zero, runs both of AlertDivideByZeroException()
and number / divisor
.
为什么会这样?
和
如何以及用什么替换 VB.net 中的 c# if 条件运算符 (?:)?
推荐答案
在 Visual Basic 中,相等运算符是 =
,而不是 ==
.您只需将 divisor == 0
更改为 divisor = 0
.
In Visual Basic, the equality operator is =
, not ==
. All you need to change is divisor == 0
to divisor = 0
.
另外,正如马克所说,你应该使用 If
而不是 IIf
.来自 If
的文档:使用三个参数调用的 If 运算符的工作方式与 IIf 函数类似,只是它使用短路求值.
由于 C# 使用短路求值,您将希望在 VB 中使用 If
来实现相同的功能.
Also, as Mark said, you should use If
instead of IIf
. From the documentation on If
: An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation.
Since C# uses short-circuit evaluation, you will want to use If
for the same functionality in VB.
这篇关于如果 VB.NET (IIf) 的条件不等于 C# (?:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!