使用内联IF语句vb.net

Ski*_*366 21 vb.net if-statement

有关代码的简要信息如下.代码采用一堆字符串并将它们如下所示,并在中间使用if语句来决定是否在其中一个上是concant.问题是If(Evaluation, "", "")抱怨说它不能是可空的或者必须是资源.当评估只是检查一个对象以确保它不是NN并且对象中的属性被检查为时,我该如何解决这个问题呢?如下:

Dim R as string = stringA & " * sample text" & _
    stringB & " * sample text2" & _
    stringC & " * sameple text3" & _
    If(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox Then ,StringD & " * sample text4" & _
    , NOTHING)
stringE & " * sample text5"
Run Code Online (Sandbox Code Playgroud)

VS正在抱怨applyValue.有任何想法吗?

应该注意的是,我已经尝试了以下只是为了看看它是否会起作用而且VS拒绝它:

Dim y As Double
Dim d As String = "string1 *" & _
    "string2 *" & _
    If(y IsNot Nothing, " * sample text4", "") & _
    "string4 *"
Run Code Online (Sandbox Code Playgroud)

这就是它标志着y:

  'IsNot' requires operands that have reference types, but this operand has the value type 'Double'.    C:\Users\Skindeep\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb 13  16  WindowsApplication1
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 45

使用IIF三元表达式评估程序

Dim R as string = stringA & " * sample text" & _
                  stringB & " * sample text2" & _
                  stringC & " * sameple text3" & _
                  IIf(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox, StringD & " * sample text4", "") & _
                  stringE & " * sample text5"
Run Code Online (Sandbox Code Playgroud)

编辑:如果您使用2008年以后的VB.NET,您也可以使用

IF(expression,truepart,falsepart)
Run Code Online (Sandbox Code Playgroud)

这甚至更好,因为它提供了短路功能.

Dim R as string = stringA & " * sample text" & _
                  stringB & " * sample text2" & _
                  stringC & " * sameple text3" & _
                  If(ApplyValue IsNot Nothing AndAlso ApplyValue.CheckedBox, StringD & " * sample text4", "") & _
                  stringE & " * sample text5"
Run Code Online (Sandbox Code Playgroud)

  • +1表示IF(表达式,truepart,falsepart). (2认同)