C#中的IIF是什么? [英] What is IIF in C#?

查看:166
本文介绍了C#中的IIF是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
iif 等效于 c#

我在 VB 中有几行使用 IIf 的代码,我正在尝试将此代码转换为 C#.

I have several lines of code using IIf in VB and I am trying to convert this code to C#.

这是我需要帮助的示例:

Here's an example where I need help:

intCurrency = IIf(or.Fields("Currency").Value = "USD", 100, 0)

如何将上面的代码行更改为 C#?C#中是否有短路求值运算符?

How do I change the above line of code to C#? Is there a short-circuit evaluation operator in C#?

推荐答案

正如一些人所建议的那样,它接近 C# 三元/条件运算符,但它不是一个确切的替代品.C# 三元运算符执行短路评估,这意味着只发生评估子句的副作用.在 VB.Net 中,Iif 函数没有实现短路,并且会评估两个副作用.

It is close to the C# ternary / conditional operator as several people have suggested but it is not an exact replacement. The C# ternary operator does short circuit evaluation meaning that only the side effect of the evaluated clause occurs. In VB.Net the Iif function does not implement short circuiting and will evaluate both side effects.

另外,VB.Net 中的 Iif 函数是弱类型的.它接受并返回类型为 Object 的值.C# 三元运算符是强类型的.

Additionally the Iif function in VB.Net is weakly typed. It accepts and returns values typed as Object. The C# ternary operator is strongly typed.

您可以编写的最接近的等效项如下.将值放入参数中会强制评估其副作用.

The closest equivalent you can write is the following. Putting the values into the arguments forces the evaluation of their side effects.

public static object Iif(bool cond, object left, object right) {
  return cond ? left : right;
}

或者稍微好用一些

public static T Iif<T>(bool cond, T left, T right) {
  return cond ? left : right;
}

这篇关于C#中的IIF是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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