26

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

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
4

1 回答 1

52

使用 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"
于 2012-12-01T16:23:19.677 回答