c# - C# 的类 Ruby 'unless'?

标签 c# ruby if-statement

有没有办法在 C# 中做类似的事情?

即。

i++ unless i > 5;

还有一个例子

weatherText = "Weather is good!" unless isWeatherBad

最佳答案

您可以使用扩展方法实现类似的目的。 例如:

public static class RubyExt
{
    public static void Unless(this Action action, bool condition)
    {
        if (!condition)
            action.Invoke();
    }
}

然后像这样使用它

int i = 4;
new Action(() => i++).Unless(i < 5);
Console.WriteLine(i); // will produce 4

new Action(() => i++).Unless(i < 1);
Console.WriteLine(i); // will produce 5

var isWeatherBad = false;
var weatherText = "Weather is nice";
new Action(() => weatherText = "Weather is good!").Unless(isWeatherBad);
Console.WriteLine(weatherText);

关于c# - C# 的类 Ruby 'unless'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10294707/

相关文章:

c# - 信号器/集线器上的 SignalR ERR_CONECTION_REFUSED

ruby - 从哈希中随机化键值对

ruby-on-rails - 我将如何检查是否在值数组中找到一个值

iphone - if 语句的问题 ||

c# - .net 核心控制台应用程序作为 Windows 服务-是否可以在不使用 Kill() 方法的情况下安全地终止已启动进程的执行?

c# - 带有 Google 的 ASP 网络文本框,如下拉搜索值

ruby-on-rails - 从 ruby​​ 守护进程中调试 osascript 执行

python - 将条件列表传递给要检查的函数

linux - "less than or equal to"运算符在 if 条件下不工作

c# - 是否可以通过命令提示符从 C# 运行 python 代码?