C# 中的 false 运算符有什么用? [英] What's the false operator in C# good for?
问题描述
C# 中有两个奇怪的运算符:
There are two weird operators in C#:
如果我理解正确,这些运算符可以用于我想使用的类型而不是布尔表达式,并且我不想提供到 bool 的隐式转换.
If 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.
假设我有以下课程:
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)
但是对于上面的所有示例,仅执行 true 运算符.那么 C# 中的 false 运算符有什么用呢?
However for all the examples above only the true operator is executed. So what's the false operator in C# good for?
推荐答案
您可以使用它来覆盖 &&
和 ||
运算符.
You can use it to override the &&
and ||
operators.
&&
和 ||
操作符不能被覆盖,但是如果你覆盖了 |
,&
、true
和 false
编译器会以完全正确的方式调用 |
和 &
你写||
和&&
.
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 &&
.
例如看这段代码(来自http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading - 我在那里发现了这个技巧;存档版本 @BiggsTRC):
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.
这篇关于C# 中的 false 运算符有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!