问题描述
有一个 IIF
相当于 C#
?或类似的快捷方式?
Is there a IIf
equivalent in C#
? Or similar shortcut?
推荐答案
C#有?三元运算符,像其他C风格的语言。然而,这不是完全等同于IIF。有两个重要的区别。
C# has the "?" ternary operator, like other C-style languages. However, this is not perfectly equivalent to iif. There are two important differences.
要解释的第一个,这个 IIF()
调用会导致DivideByZero例外,即使前pression是真实的,因为 IIF
只是一个功能,所有的参数必须在调用之前进行评估:
To explain the first, this iif()
call would cause a DivideByZero exception even though the expression is true because iif
is just a function and all arguments must be evaluated before calling:
iif(true, 1, 1/0)
换句话说,IIF做的没有的短路,传统意义上的,因为你的问题表示。在另一方面,这个三元EX pression做,所以是完美的罚款:
Put another way, iif does not short circuit in the traditional sense, as your question indicates. On the other hand, this ternary expression does and so is perfectly fine:
(true)?1:1/0;
另一个区别是, IIF
不是类型安全。它接受并返回一个类型对象
的参数。三元运算符使用类型推断知道什么类型的它在处理。请注意,您可以解决这个问题很容易用一个通用的实现,但开箱这就是事情是这样的。
The other difference is that iif
is not type safe. It accepts and returns arguments of type object
. The ternary operator uses type inference to know what type it's dealing with. Note that you can fix this very easily with a generic implementation, but out of the box that's the way it is.
如果你真的想IIF()在C#中,你可以把它:
If you really want iif() in C#, you can have it:
object iif(bool expression, object truePart, object falsePart)
{return expression?truePart:falsePart; }
或通用/类型安全的实现:
or a generic/type-safe implementation:
T iif<T>(bool expression, T truePart, T falsePart)
{ return expression?truePart:falsePart;}
在另一方面,如果你想三元运算符在VB,Visual Studio 2008和更高版本提供了新的如果
的运算符的的作品更多如C#的三元。它使用类型推断知道它的返回,这是运营商,而不是一个函数,所以没有讨厌的除数为零的问题。
On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If
operator that works more like C#'s ternary. It uses type inference to know what it's returning, and it's an operator rather than a function so there's no pesky divide-by-zero issues.
这篇关于IIF在C#中相当于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!