zoukankan      html  css  js  c++  java
  • 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("-----------------");
            }
        }
  • 相关阅读:
    从 i++ 和 ++i 说起局部变量表和操作数栈
    数据库连接情况查询相关sql语句
    db2相关语句
    BeanUtils源码详解
    Spring注解驱动开发之AOP
    Spring注解驱动开发之IOC
    正则表达式
    linux特殊符号
    linux下面如何让一个软件/命令开机自启动
    linux文件属性
  • 原文地址:https://www.cnblogs.com/FlyCat/p/2579988.html
Copyright © 2011-2022 走看看