使用内联IF语句vb.net

时间:2012-12-01 16:16:50

标签: 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"

VS正在抱怨applyValue。任何想法?

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

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

这是标志着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

1 个答案:

答案 0 :(得分:41)

使用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"

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

IF(expression,truepart,falsepart)

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

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"