0

独自の条件ステートメントを記述したり、現在のステートメントをオーバーロードしたりすることは可能ですか?

私が実際にやりたいのは

object obj = null;

if(obj) // or something like if(1==1 || obj && obj.Value)
    // do something
else
    // do someotherstuff
4

1 に答える 1

1

正確ではありませんが、あなたが言及した特定のケースでは、特定のクラスのインスタンスを評価する方法をtrue/にオーバーロードできfalseます。

// returns true if the object evaluates to true
public static bool operator true(YourClass x)
{
    return x != null;
}

// returns true if the object evaluates to false
public static bool operator false(YourClass x) 
{
    return x == null;
}

そうすれば、これを行うことができます:

YourClass x = new YourClass();

if (x) // same as "if (x != null)" (defined in operator true)
    // do something
else if (!x) // same as "if (x == null)" (defined in operator false)
    // do someotherstuff

詳細:
trueオペレーター(MSDN)
falseオペレーター(MSDN)

于 2013-03-27T14:24:09.373 に答える