C#中:从布尔继承? [英] C#: Inherit from Boolean?

查看:122
本文介绍了C#中:从布尔继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(如何)我可以从布尔继承?
(或者让我的类具有可比性=操作为Boolean)

  MyClass类:布尔
{
    公共MyClass的()
    {
        该=真;
    }
}
类节目
{
    公共项目()
    {
        MyClass的MyClass的=新MyClass的();
        如果(MyClass的== true)而
            //做一点事...
        其他
            //做别的事情......
    }
}


解决方案

简单的例子:

 公共类MyClass的{
    私人布尔IsTrue运算= TRUE;    公共静态布尔运算符==(MyClass的一个,布尔B)
    {
        如果(A == NULL)
        {
            返回false;
        }        返回a.isTrue == B:
    }    公共静态布尔运算符!=(MyClass的一个,布尔B)
    {
        返回(A == B)!;
    }
}

在某处code,你可以比较布尔值你的对象:

  MyClass的一个=新MyClass的();
如果(A ==真){//它a.isTrue财产比较在==操作符重载方法定义
   // ...
}

(how) can I Inherit from Boolean? (Or make my class comparable to Boolean with '=' Operator)

class MyClass : Boolean
{
    public MyClass()
    {
        this = true;
    }
}
class Program
{
    public Program()
    {
        MyClass myClass = new MyClass();
        if(myClass == true)
            //do something...
        else
            //do something else...
    }
}

解决方案

Simple example:

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);
    }
}

somewhere in code you can compare your object with boolean value:

MyClass a = new MyClass();
if ( a == true ) { // it compares with a.isTrue property as defined in == operator overloading method
   // ...
}

这篇关于C#中:从布尔继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆