有两个奇怪的运营商在C#: 的真正的运营商 的假运营商
如果我理解这一权利,这些运营商可以在其中我想用一个布尔EX pression而不是和类型来使用,我并不想提供一个隐式转换为bool。
让我们说我有以下类:
公共类的MyType
{
公共只读int值;
公共MyType的(int值)
{
值=价值;
}
公共静态布尔运算符真(的MyType MT)
{
返回mt.Value> 0;
}
公共静态布尔运算符假(MyType的MT)
{
返回mt.Value< 0;
}
}
所以,我可以写下面的code:
的MyType mTrue =新的MyType(100);
MyType的mFalse =新的MyType(-100);
MyType的mDontKnow =新的MyType(0);
如果(mTrue)
{
// 做一点事。
}
而(mFalse)
{
//做别的事情。
}
做
{
//另一个code来这里。
}而(mDontKnow)
时,执行然而对于所有以上:只有真正的操作者的例子。那么,什么是用C#好假运营商?
注:更多的例子可以发现here, here和here.
解决方案您可以用它来重写&功放;&安培;
和 ||
运营商。
在&功放;&安培;
和 ||
运营商不能被覆盖,但如果重写 |
,&安培;
,真
和假
在完全正确的方式,编译器会调用 |
和&安培;
当你写 ||
和&功放;&安培;
例如,看这个code(从 HTTP: //ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - 在那里我发现了这一招,存档版本由@BiggsTRC ):
公共静态AbstractCriterion运营商及(AbstractCriterion LHS,AbstractCriterion RHS)
{
返回新ANDEX pression(左,右);
}
公共静态AbstractCriterion运营商|(AbstractCriterion LHS,AbstractCriterion RHS)
{
返回新OREX pression(左,右);
}
公共静态布尔运算符假(AbstractCriterion标准)
{
返回false;
}
公共静态布尔运算符真(AbstractCriterion标准)
{
返回false;
}
这是明显的副作用,而不是这样它旨在被使用,但它是有用的。
There are two weird operators in C#:
the true operator the false operatorIf I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool.
Let's say I have a following class:
public class MyType
{
public readonly int Value;
public MyType(int value)
{
Value = value;
}
public static bool operator true (MyType mt)
{
return mt.Value > 0;
}
public static bool operator false (MyType mt)
{
return mt.Value < 0;
}
}
So I can write the following code:
MyType mTrue = new MyType(100);
MyType mFalse = new MyType(-100);
MyType mDontKnow = new MyType(0);
if (mTrue)
{
// Do something.
}
while (mFalse)
{
// Do something else.
}
do
{
// Another code comes here.
} while (mDontKnow)
However for all the examples above only the true operator is executed. So what's the false operator in C# good for?
Note: More examples can be found here, here and here.
解决方案You can use it to override the &&
and ||
operators.
The &&
and ||
operators can't be overridden, but if you override |
, &
, true
and false
in exactly the right way the compiler will call |
and &
when you write ||
and &&
.
For example, look at this code (from http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - where I found out about this trick; archived version by @BiggsTRC):
public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new AndExpression(lhs, rhs);
}
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new OrExpression(lhs, rhs);
}
public static bool operator false(AbstractCriterion criteria)
{
return false;
}
public static bool operator true(AbstractCriterion criteria)
{
return false;
}
This is obviously a side effect and not the way it's intended to be used, but it is useful.