如果VB.NET(IIf)的条件不等于C#(?:)

Beh*_*zad 2 c# vb.net if-statement iif

VB.NET中的IIf函数:

IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
Run Code Online (Sandbox Code Playgroud)

C#条件运算符(?:)完全不相等:

condition ? first_expression : second_expression;
Run Code Online (Sandbox Code Playgroud)

当我将一些代码从c#转换为vb.net时,我理解转换后的代码无法正常工作,因为在vb.net中,如果条件在检查条件之前被评估为真假部分!

例如,C#:

public int Divide(int number, int divisor)
{
    var result = (divisor == 0) 
                 ? AlertDivideByZeroException() 
                 : number / divisor;

    return result;
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

现在,我的c#代码执行成功,但vb.net代码每次divisor都不等于零,运行AlertDivideByZeroException()number / divisor.

为什么会这样?

如何以及如何在VB.net中替换c#if-conditional运算符(?:)?

Jas*_*zun 6

在Visual Basic中,等于运算符=不是==.所有你需要改变的是divisor == 0divisor = 0.

另外,正如马克所说,你应该用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中使用相同的功能.