语法错误使用IIf [英] Syntax error using IIf

查看:154
本文介绍了语法错误使用IIf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我希望的简单问题。我今天了解了IIF,并希望在某些情况下实现它,以节省几行。

  IIF(isnumeric(inputs)继续下一步,调用notnum)

这是红色的意思是有一个语法错误,如何修复?我已经扫描MSDN文章,所以我不会在这里懒惰。

解决方案

这不是如何



这是一个功能,而不是一个语句:你使用它的返回值就像你将使用任何其他功能 - 使用它来控制流程是一个坏主意。



一目了然, IIf 有点像其他语言的三元运算符


 code> string result =(foo == 0?Zero:NonZero); 


条件,值为true,值为false,值是相同的类型。



这是为了转换:

 如果foo = 0 
Debug.PrintZero
Else
Debug.PrintNonZero
End If

进入:

  Debug.Print IIf(foo = 0 ,零,非零)

请小心, IIf 评估 部分,所以你不会有副作用。例如,调用以下 Foo 程序:

  Public Sub Foo )
Debug.Print IIf(IsNumeric(42),A,B)
End Sub

私有函数A()As String
Debug.Printin A
A =A
结束函数

私有函数B()As String
B中的Debug.Print
B =B
结束功能

输出结果

 在A 
中B
A

这就是为什么使用 IIf 来控制流是不理想的。但是当真结果错误结果参数是常量表达式时,如果明智地使用,它可以通过转动$ $ c来帮助提高代码的可读性$ c> If ... Else ... End If 阻止成一个简单的函数调用。



像所有的好东西一样,最好不要滥用它。


This is a simple question I hope. I learned about IIf today and want to implement it in some cases to save a few lines.

IIF(isnumeric(inputs), resume next, call notnum)

This is in red meaning there is a syntax error, how fix this? I have scanned MSDN article on this so I am not being lazy here.

解决方案

That's not how the IIf function works.

It's a function, not a statement: you use its return value like you would with any other function - using it for control flow is a bad idea.

At a glance, IIf works a little bit like the ternary operator does in other languages:

string result = (foo == 0 ? "Zero" : "NonZero");

Condition, value if true, value if false, and both possible values are of the same type.

It's for turning this:

If foo = 0
    Debug.Print "Zero"
Else
    Debug.Print "NonZero"
End If

Into this:

Debug.Print IIf(foo = 0, "Zero", "NonZero")

Be careful though, IIf evaluates both the true and the false parts, so you will not want to have side-effects there. For example, calling the below Foo procedure:

Public Sub Foo()
    Debug.Print IIf(IsNumeric(42), A, B)
End Sub

Private Function A() As String
    Debug.Print "in A"
    A = "A"
End Function

Private Function B() As String
    Debug.Print "in B"
    B = "B"
End Function

Results in this output:

in A
in B
A

That's why using IIf for control flow isn't ideal. But when the true result and false result arguments are constant expressions, if used judiciously, it can help improve your code's readability by turning If...Else...End If blocks into a simple function call.

Like all good things, best not abuse it.

这篇关于语法错误使用IIf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆