C# 操作符重载 模拟String

模拟String,让引用类型的使用像值类型一样

    class MyString
    {
        private static Dictionary<string, MyString> dic = new Dictionary<string, MyString>();
        string s;
        public MyString(string s)
        {
           this.s = s;
           dic[s] = this;
        }

        public static implicit operator MyString(string value)
        {
            if (dic.ContainsKey(value))
            {
                return dic[value];
            }
            return new MyString(value);
        }


        public static bool operator ==(MyString s1, MyString s2)
        {
            return s1.ToString() == s2.ToString();
        }
        public static bool operator !=(MyString s1, MyString s2)
        {
            return !(s1.ToString() == s2.ToString());
        }


        public override string ToString()
        {
            return s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyString ms1 = "1111";
            MyString ms2 = "1111";
            Test(ms1, ms2);

            ms2 = ms1;
            ms1 = ms1 + "changed";
            Test(ms1, ms2);

            Test(ms1, ms2);

            string s1 = "test";
            string s2 = "test";
            Test(s1, s2);

            s2 = s1;
            s1 = s1 + "change";
            Test(s1, s2);
        }
        static void Test(object obj1,object obj2)
        {
            Console.WriteLine("ob1:{0}  obj1:{1} ",obj1,obj2);
            Console.WriteLine("ob1==obj1: " + (obj1 == obj2).ToString());
            Console.WriteLine("引用相等:"+ Object.ReferenceEquals(obj1, obj2).ToString());
            Console.WriteLine("-----------------");
        }
    }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值