C# 泛型类型相等运算符
C# generic types equality operator
来自https://msdn.microsoft.com/en-us/library/d5x73970.aspx
When applying the where T : class constraint, avoid the == and !=
operators on the type parameter because these operators will test for
reference identity only, not for value equality. This is the case even
if these operators are overloaded in a type that is used as an
argument. The following code illustrates this point; the output is
false even though the String class overloads the == operator.
public static void OpTest<T>(T s, T t) where T : class
{
System.Console.WriteLine(s == t);
}
static void Main()
{
string s1 = "target";
System.Text.StringBuilder sb = new System.Text.StringBuilder("target");
string s2 = sb.ToString();
OpTest<string>(s1, s2);
}
一切正常,直到我用同样的方法尝试跟随
static void Main()
{
string s1 = "target";
string s2 = "target";
OpTest<string>(s1, s2);
}
它输出 'True',s1 和 s2 引用内存中的不同对象,即使它们具有相同的值,对吗?我错过了什么吗?
字符串在 .NET 中是固定的,所以当您这样做时
string s1 = "target";
string s2 = "target";
它们都指向同一个对象。这就是 MSDN 示例使用 StringBuilder
的原因,这会欺骗 CLR 创建另一个具有相同值的字符串对象,以便泛型方法中的运算符测试将 return false.
来自https://msdn.microsoft.com/en-us/library/d5x73970.aspx
When applying the where T : class constraint, avoid the == and != operators on the type parameter because these operators will test for reference identity only, not for value equality. This is the case even if these operators are overloaded in a type that is used as an argument. The following code illustrates this point; the output is false even though the String class overloads the == operator.
public static void OpTest<T>(T s, T t) where T : class
{
System.Console.WriteLine(s == t);
}
static void Main()
{
string s1 = "target";
System.Text.StringBuilder sb = new System.Text.StringBuilder("target");
string s2 = sb.ToString();
OpTest<string>(s1, s2);
}
一切正常,直到我用同样的方法尝试跟随
static void Main()
{
string s1 = "target";
string s2 = "target";
OpTest<string>(s1, s2);
}
它输出 'True',s1 和 s2 引用内存中的不同对象,即使它们具有相同的值,对吗?我错过了什么吗?
字符串在 .NET 中是固定的,所以当您这样做时
string s1 = "target";
string s2 = "target";
它们都指向同一个对象。这就是 MSDN 示例使用 StringBuilder
的原因,这会欺骗 CLR 创建另一个具有相同值的字符串对象,以便泛型方法中的运算符测试将 return false.