首页 > 代码库 > C#一元运算重载的深入理解

C#一元运算重载的深入理解

using System;
using System.Diagnostics;
using System.Text;
using System.Collections;
using System.Collections.Generic;
delegate string DTE(int x, string s);

class MYTestX
{
    public class CDT
    {
        public CDT(int x)
        {
            this.x = x;
        }
        int x = 10;

        //类型转换只能是public static implicit形式或public static explicit形式
        //,这里的implicit与explicit并不是返回值类型,而是修饰符,说明是隐式转换还是显式转换
        //因此不能写成public static bool operator bool(CDT odt)这样的形式,编译会出错
        //应用场景 
        //1: CDT ot = new CDT(); if(ot){}
        //2: CDT ot = new CDT(); bool b = ot;
        public static implicit operator bool(CDT odt)
        {
            Console.WriteLine("operator bool------------------");

            return odt != null;
        }
        //应用场景:
        //CDT ot = new CDT(); string s = (string) ot
        public static explicit operator string(CDT odt)
        {
            Console.WriteLine("operator string------------------");
            return odt.ToString();
        }
        //应用场景:
        //CDT ot = new CDT(); string s = ot
        public static implicit operator int(CDT odt)
        {
            Console.WriteLine("operator string------------------");
            return odt.x;
        }

        //重载 true false运算符(注意的MSDN文档说明中说true和false是运算符,就像 +,-普通运算符一样)
        //两者必须一起重载。其实就相当于重载一个bool运算符的效果, 并不完全等价
        //应用场景:
        //CDT ot = new CDT(); if(ot){}
        //不能用于: CDT ot = new CDT();  bool b = ot; bool b2 = (bool)ot;
        public static bool operator true(CDT odt){

            return odt != null;
        }
        public static bool operator false(CDT odt)
        {

            return odt == null;
        }
    }
    class CDTX { }

    //public void TestLimitX(CDTX ot)//编译错误:CDTX的访问权限不能小于TestLimitX的访问权限
    //{
    //}
    public static void TestLimit(CDT ot)//可以访问
    {
        if (ot) { }//调用operator ture
        bool b = ot;//调用operator bool,若无此重载,则编译错误,并不会调用operator ture 或ooperator false
        string st = (string)ot; //可以转换,调用重载的显示的string转换运算符
        CDTX otx = new CDTX();
        //string stx = (string)otx; //编译出错,不能转换
        Console.WriteLine(b);
    }
    static void Main(string[] args)
    {
        TestLimit(new CDT(112));
    }

}

 

C#一元运算重载的深入理解