.net - 如何避免在 IIF 中遇到错误的部分?

标签 .net vb.net iif

我正在尝试在 vb.net 中使用 IIF,这是我的代码

Dim arr as new MyClass("ABC")
MyAnotherMethod(IIf(arr.SelectedValue.Count < 1, Nothing, arr.SelectedValue(0).Value),"xxx","yyy","zzz")

上面的 IIF 将运行到 true 部分,但是在我运行此代码后,我收到以下消息:

Index was outside the bounds of the array.



我认为原因是虽然应该运行 true 部分,但 arr.SelectedValue(0).Value 已传递到 IIF,因此仍引用 false 部分。

有没有像“andalso”这样的逻辑适合我的情况?以免跑假部分。

非常感谢!

最佳答案

您需要使用 IF Operator而不是 IIF 函数

“使用三个参数调用的 If 运算符的工作方式类似于 IIf 函数,但它使用短路评估”

它也是类型安全的,而 IIF 不是,所以你真的应该使用它。看看这些工作示例:

    Dim i As Integer

    'compiles if option strict is off (this is bad)
    i = IIf(True, "foo", 4) 

    'compiles even if option strict on, but results in a runtime error (this is even worse)
    i = CInt(IIf(True, "foo", 4)) 

    'won't compile (this is good because the compiler spotted the mistake for you)
    i = If(True, "foo", 4) 

关于.net - 如何避免在 IIF 中遇到错误的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11538811/

相关文章:

vb.net - 变量值传递到另一个表单,VB.NET

javascript - 回发后防止页面滚动并保持位置

sql - 在sql查询中使用iif而无需其他 Access

sql - 如果日期早于当前月份,则将日期转换为当前月份的第一天

vb.net - IIf 抛出奇怪的异常

.net - 如何创建一个没有边框且只能通过 handle 调整大小的 WPF 窗口?

c# - 使用 WinSCP .NET Assembly 防止通过 FTP 传输不完整的文件

来自客户端程序的 MySQL 连接仍然存在

c++ - 创建非托管常规 MFC DLL 并从托管 C++ .NET 应用程序调用它时出现问题

c# - 作为枚举的键值对