模拟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("-----------------");
}
}