C#的重载操作符

 
 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Xml;
namespace CSharpConsole
{
    class T
    {
        public int val=3;
        public override int GetHashCode()
        {
            return val*10007;
        }
        public override bool Equals(object obj)//如果要定义Equal,一般要定义GetHashCode
        {
            return true;
        }
        public static bool operator ==(T t1, T t2)//关系重载运算符,注意定义了==和!=一般情况下,就要定义Object.Equal(object o);
        {
            if (t1.val == t2.val)     return true;
                return false;
        }
        public static bool operator !=(T t1, T t2)//定义了==,那也必须定义!=
        {
            return !(t1 == t2);
        }
        public static explicit operator double(T tobj)//重载转换操作符,有个奇怪的定义,不需要声明返回值,因为强制转换就是返回类型
        {
            return 3;
        }
        //布尔操作符,注意布尔操作符也可以像double转换操作符那样使用,两种方法都可以
        public static bool operator true(T tobj)//定义了true就必须定义false
        {
            return (tobj.val != 0);
        }
        public static bool operator false(T tobj)//定义了true就必须定义false
        {
            return (tobj.val == 0);
        }
        public static T operator ++(T t)//只需要制定前置++/--,编译器会自动生成后置++/--,必须新建一个,不然就....
        {
            T tm = new T();
            tm.val = t.val;
            (tm.val)++;
            return tm;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            T t = new T();
            //使用重载转换操作符
            Console.WriteLine(((double)t).GetType());
            //使用布尔操作符
            if (t)
            {
                ///
            }
            T t1 = new T();
            Console.WriteLine(t1.val);
            Console.WriteLine((++t1).val);
        }
    }
}


你可能感兴趣的:(object,String,C#,equals,Class,编译器)