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

更多信息:
真运算符 (MSDN)
假运算符 (MSDN)

于 2013-03-27T14:24:09.373 回答