使用内联 IF 语句 vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13661200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:29:14  来源:igfitidea点击:

Using inline IF statement vb.net

vb.netif-statement

提问by Skindeep2366

Brief info on the code is as follows. The code takes a bunch of strings and concants them as follows with a if statement in the middle that decides whether to concant or not on one of them. The problem is the If(Evaluation, "", "")is complaining saying that it must not be nullable or must be a resource.. How do I work around this when the Evaluation simply checks an object to make sure it IsNot Nothing and also that a property in the object is checked as follows:

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

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 is complaining about the applyValue. Any Ideas?

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

Should be noted that I have tried the following just to see if it would work and VS is rejecting it:

应该注意的是,我已经尝试了以下只是为了看看它是否有效并且 VS 拒绝了它:

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

This is what it is flagging the y with:

这是它标记 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

回答by Steve

Use the IIF ternary expression evaluator

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

EDIT: If you use VB.NET from ver 2008 onward you could use also the

编辑:如果您从 2008 年开始使用 VB.NET,您也可以使用

IF(expression,truepart,falsepart)

and this is even better because it provides the short-circuit functionality.

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

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"