(how)我可以继承布尔值吗? (或者使我的班级与'='运算符的布尔可比)
class MyClass : Boolean
{
public MyClass()
{
this = true;
}
}
class Program
{
public Program()
{
MyClass myClass = new MyClass();
if(myClass == true)
//do something...
else
//do something else...
}
}
答案 0 :(得分:10)
你做不到。 System.Boolean
是一个结构,你不能从结构派生。
现在,你为什么要这样做呢?什么是更大的目的?
你可以在你的班级中包含一个隐式转换运算符bool
,但我个人不会。我几乎总是喜欢公开一个属性,所以你要写:
if (myValue.MyProperty)
......我认为这可以保持清晰。但是如果你能给我们更多的真实的背景,我们可能会提供更具体的建议。
答案 1 :(得分:6)
简单示例:
public class MyClass {
private bool isTrue = true;
public static bool operator ==(MyClass a, bool b)
{
if (a == null)
{
return false;
}
return a.isTrue == b;
}
public static bool operator !=(MyClass a, bool b)
{
return !(a == b);
}
}
在代码中的某处,您可以将对象与布尔值进行比较:
MyClass a = new MyClass();
if ( a == true ) { // it compares with a.isTrue property as defined in == operator overloading method
// ...
}
答案 2 :(得分:2)
您可以使用隐式转换运算符来获取此代码:
class MyClass {
public bool Value { get; set; }
public MyClass() {
Value = true;
}
public static implicit operator bool(MyClass m) {
return m != null && m.Value;
}
}
class Program {
public static void Main() {
var myClass = new MyClass();
if (myClass) { // MyClass can be treated like a Boolean
Console.WriteLine("myClass is true");
}
else {
Console.WriteLine("myClass is false");
}
}
}
可以如上使用:
if (myClass) ...
或者像这样:
if (myClass == true) ...
答案 3 :(得分:0)
虽然你的例子不起作用,你可以为你自己的类做一些类似的测试,如果一个等于另一个的值。
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
{
return !(a == b);
}
答案 4 :(得分:0)
你可以通过覆盖==运算符(“或使我的类可比......”)。我认为Jon Skeet忽略了这个问题的一部分。
答案 5 :(得分:0)
如果您希望能够在'if'语句中使用您的值,请定义operator true
and operator false
(以及&
和|
运算符(如果您要使用&&
}和||
。)(VB equivalents)
要回答更多问题,我必须知道你要做什么(换句话说,为什么不直接使用bool
?)