有没有办法在 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/