操作员如何重载真假工作?
您可以重载运算符true和false我查看了示例并找到了这个http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx
我完全不明白他们是如何工作的。 我知道如果我写if(obj)并且true返回true则执行if。 什么是错误的回报并不重要。 但假工作怎么样? 在该文档中,建议&&运算符使用它。 我写了下面的代码。 我不知道如何让&&编译。 || 也给了我一个编译错误。 我怎么会被称为虚假? 以及如何获得&&和|| 上class?
var ts= new MyTimeSpan();// ts += ts; if (ts){ Console.WriteLine("Is true"); } else { Console.WriteLine("not true"); } //Console.WriteLine(ts && ts ? "Y" : "N"); class MyTimeSpan { public static MyTimeSpan operator +(MyTimeSpan t, MyTimeSpan t2) { return new MyTimeSpan(); } public static bool operator true(MyTimeSpan t) { return true; } public static bool operator false(MyTimeSpan t) { return false; } }
短路操作符的定义属性是,如果左侧已经确定结果,则不需要评估右侧。 对于or
如果左侧为true
,结果在任何情况下都是真的,并且没有必要评估右侧。 对于and
它是相同的,除非如果左侧为false
则结果将为假。
你需要重载两个|
并且true
得到||
。 &&
和false
得到&&
。
a||b
对应像op_true(a)?a:(a|b)
。 因此,如果true运算符返回true,则不需要计算b的表达式。
a&&b
对应像op_false(a)?a:(a&b)
。 因此,如果false运算符返回true,则不需要计算b的表达式。
在创建自定义布尔类型时,重载短路运算符很有用,例如可空的DBBool
(参见DBBool
)
当重载true
和false
运算符时,它们不仅返回true
和false
,它们用于确定您的类型的值是否被认为是true或false。
例如,如果类中的零值表示false,则非零值表示true:
public static bool operator true(MyTimeSpan t) { return t.Value != 0; } public static bool operator false(MyTimeSpan t) { return t.Value == 0; }
由于运算符彼此相反,编译器不需要同时使用它们来确定值是true还是false。 如果编写if(obj)
,编译器将使用true
运算符来确定该值是否为true。
您需要为&&和|覆盖&运算符 或||。
像这样的东西:(只是一个虚拟代码)
public static MyTimeSpan operator &(MyTimeSpan t, MyTimeSpan s) { return t; } public static MyTimeSpan operator |(MyTimeSpan t, MyTimeSpan s) { return t; }