如果 VB.NET (IIf) 的条件不等于 C# (?:)
If Condition of VB.NET (IIf) is not equal by C# (?:)
VB.NET中的IIf function:
IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
不完全等于 C# conditional operator (?:) :
condition ? first_expression : second_expression;
当我将一些代码从 c# 转换为 vb.net 时,我了解到转换后的代码无法正常工作,因为在 vb.net if 条件中,在检查条件之前评估了 true 和 false 部分!
例如,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# 代码已成功执行,但 vb.net 代码每次 divisor
不等于零时,都会运行 AlertDivideByZeroException()
和 number / divisor
。
为什么会这样?
和
如何以及用什么替换 VB.net 中的 c# if 条件运算符 (?:)?
在 Visual Basic 中,相等运算符是 =
,而不是 ==
。您只需将 divisor == 0
更改为 divisor = 0
。
此外,正如 Mark 所说,您应该使用 If
而不是 IIf
。来自 If
的文档:An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation.
由于 C# 使用短路评估,因此您需要使用 If
来实现 VB 中的相同功能。
VB.NET中的IIf function:
IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
不完全等于 C# conditional operator (?:) :
condition ? first_expression : second_expression;
当我将一些代码从 c# 转换为 vb.net 时,我了解到转换后的代码无法正常工作,因为在 vb.net if 条件中,在检查条件之前评估了 true 和 false 部分!
例如,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# 代码已成功执行,但 vb.net 代码每次 divisor
不等于零时,都会运行 AlertDivideByZeroException()
和 number / divisor
。
为什么会这样?
和
如何以及用什么替换 VB.net 中的 c# if 条件运算符 (?:)?
在 Visual Basic 中,相等运算符是 =
,而不是 ==
。您只需将 divisor == 0
更改为 divisor = 0
。
此外,正如 Mark 所说,您应该使用 If
而不是 IIf
。来自 If
的文档:An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation.
由于 C# 使用短路评估,因此您需要使用 If
来实现 VB 中的相同功能。