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

时间:2015-07-07 22:15:43

标签: c# vb.net if-statement iif

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中,如果在检查条件之前对条件的真假部分进行了评估,则会对其进行评估!

例如,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 / divisor

为什么会这样?

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

1 个答案:

答案 0 :(得分:6)

在Visual Basic中,相等运算符为=,而不是==。您需要更改的是divisor == 0divisor = 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#使用短路评估,因此您需要在VB中使用If来实现相同的功能。