16

C#で似たようなことをする方法はありますか?

すなわち。

i++ unless i > 5;

ここに別の例があります

weatherText = "Weather is good!" unless isWeatherBad
4

4 に答える 4

20

拡張メソッドを使用すると、このようなことを実現できます。例えば:

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);
于 2012-04-24T09:20:47.990 に答える
12

どうですか :

if (i<=5) i++;

if (!(i>5)) i++;もうまくいくでしょう。


ヒント:unless正確に同等のものはありません。

于 2012-04-24T08:57:52.117 に答える
0

編集:Rubyunlessは私の考えのようにループしないため、これは間違っています。私はあまりにも速く答えました。

下の間違った答え


基本キーワードと演算子を使用した構文に最も近い構文は、次のようなものです。

int x = 0;
do 
{
    x++;
} while (x < 5);
于 2012-04-24T08:58:06.807 に答える
0

三項?:演算子があります:

i = i > 5 ? i : i + 1
//if i>5 then i, else i++

(ルビーコードが私が思うことを意味すると仮定して)

于 2012-04-24T08:58:20.090 に答える