使用 VB.NET IIF 我得到 NullReferenceException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/428959/
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-03 10:57:16  来源:igfitidea点击:

Using VB.NET IIF I get NullReferenceException

.netvb.netnullreferenceexception

提问by Nathan Koop

I am doing a little debugging, and so I want to log the eventArgs value

我正在做一些调试,所以我想记录 eventArgs 值

I have a simple line that basically does:

我有一个简单的行,基本上可以:

logLine = "e.Value: " + IIf(e.Value Is Nothing, "", e.Value.ToString())

The way I understand the IIF function, if the e.Value is Nothing (null) then it should return the empty string, if not it should return the .ToString of the value. I am, however getting a NullReferenceException. This doesn't make sense to me.

我理解 IIF 函数的方式,如果 e.Value 是 Nothing (null) 那么它应该返回空字符串,如果不是它应该返回值的 .ToString 。但是,我收到了 NullReferenceException。这对我来说没有意义。

Any idea's?

有任何想法吗?

回答by bdukes

IIfis an actual function, so all arguments get evaluated. The Ifkeyword was added to VB.NET 2008 to provide the short-circuit functionality you're expecting.

IIf是一个实际的函数,因此所有参数都会被评估。该如果关键字加入到2008年VB.NET提供你期待短路功能。

Try

尝试

logLine = "e.Value: " + If(e.Value Is Nothing, "", e.Value.ToString())

回答by Chris Farmer

VB does not do short-circuiting evaluation in Iif. In your case, e.Value.ToString() is being evaluated no matter whether e.Value is nothing.

VB 在 Iif 中不做短路评估。在你的情况下, e.Value.ToString() 正在被评估,无论 e.Value 是什么。

回答by Philip Fourie

This is the expected behaviour.

这是预期的行为。

IIFis a function; therefore the parameters for the function will be evaluated before sending it to the function.

IIF是一个函数;因此,函数的参数将在将其发送到函数之前进行评估。

In contrast, the ternary operator in C# is a language construct that prevents the evaluation of the second parameter if the expression of the ternary is true.

相比之下,C# 中的三元运算符是一种语言结构,如果三元表达式为真,它会阻止对第二个参数的求值。