【问题标题】:Issue with ternary operator syntax in VB.NETVB.NET 中的三元运算符语法问题
【发布时间】:2014-08-16 12:49:22
【问题描述】:

我正在尝试在 vb.net 中使用三元运算符,但要确定要附加到字符串的内容,但我遇到了语法问题...

为什么第三行在==生成表达式预期错误

上给出错误
Dim sb As New StringBuilder
Dim bln As Boolean
bln == true ? sb.append("True") : sb.Append("False")
' this also doesn't work
bln ? sb.append("True") : sb.Append("False")

【问题讨论】:

    标签: vb.net syntax ternary-operator


    【解决方案1】:

    VB.NET中的三元运算符是这样使用的:

    If(<Test Statement>, <Result if True>, <Result if False>)
    

    所以你可以这样做:

    sb.Append(If(bln, "True", "False"))
    

    但这将是完成您需要的更好的方法:

    sb.Append(CStr(bln))
    

    【讨论】:

      【解决方案2】:

      在基于 C 的语言中,它曾经是这样的:

      String name = (person == null) ? "" : person.Name;
      

      但在 VB.Net 中是这样的:

      Dim name As String = If(person Is Nothing, "", person.Name)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-24
        • 2011-07-13
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        相关资源
        最近更新 更多