是否可以编写自己的条件语句或过载当前条件语句?
我真正想做的是
object obj = null;
if(obj) // or something like if(1==1 || obj && obj.Value)
// do something
else
// do someotherstuff
答案 0 :(得分: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