条件是C#和VB的差异

Nyr*_*yra 10 c# vb.net

为什么条件if在VB中不需要处理条件的直接转换.例如在C#中,这很好......

        bool i = false;

        i = (1<2)? true:false;

        int x = i? 5:6;
Run Code Online (Sandbox Code Playgroud)

但如果我想在VB中使用相同的东西,我将不得不施展它

Dim i as Boolean = CBool(IIF(1<2, True, False))
Dim x as Integer = CInt(IIF(i, 5, 6))
Run Code Online (Sandbox Code Playgroud)

我不明白为什么C#会做转换,为什么VB不做.如果我被浇铸在我的C#条件语句如

bool i = Convert.ToBoolean((1<2)? True: False);
int x = Convert.ToInt32(i? 5:6);
Run Code Online (Sandbox Code Playgroud)

另外,是的,我知道IIF返回类型对象,但我会认为C#的确可以返回的不仅仅是True | False; 在我看来,C#处理隐式转换.

Ry-*_*Ry- 26

IIf是一个函数,并不等同于C#?:,它是一个运算符.

运算符版本已经在VB.NET中存在了一段时间,并且刚刚被调用If:

Dim i As Boolean = If(1 < 2, True, False)
Run Code Online (Sandbox Code Playgroud)

......当然,这是毫无意义的,应该写成:

Dim i As Boolean = 1 < 2
Run Code Online (Sandbox Code Playgroud)

......或者Option Infer:

Dim i = 1 < 2
Run Code Online (Sandbox Code Playgroud)

  • @alykins:它不存在于VB中,只存在于VB.NET中,并且仅存在于2008年以来. (2认同)

Nic*_*ick 6

此代码将显示IIf函数和If运算符之间的区别.因为IIf是一个函数,它必须评估要传递给函数的所有参数.

Sub Main
    dim i as integer
    i = If(True, GetValue(), ThrowException()) 'Sets i = 1. The false part is not evaluated because the condition is True
    i = IIf(True, GetValue(), ThrowException()) 'Throws an exception. The true and false parts are both evaluated before the condition is checked
End Sub

Function GetValue As Integer
    Return 1
End Function

Function ThrowException As Integer
    Throw New Exception
    Return 0
End Function
Run Code Online (Sandbox Code Playgroud)