独自の条件ステートメントを記述したり、現在のステートメントをオーバーロードしたりすることは可能ですか?
私が実際にやりたいのは
object obj = null;
if(obj) // or something like if(1==1 || obj && obj.Value)
// do something
else
// do someotherstuff
独自の条件ステートメントを記述したり、現在のステートメントをオーバーロードしたりすることは可能ですか?
私が実際にやりたいのは
object obj = null;
if(obj) // or something like if(1==1 || obj && obj.Value)
// do something
else
// do someotherstuff
正確ではありませんが、あなたが言及した特定のケースでは、特定のクラスのインスタンスを評価する方法を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