简体   繁体   English

C#泛型类型相等运算符

[英]C# generic types equality operator

From https://msdn.microsoft.com/en-us/library/d5x73970.aspx 来自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. 在应用where T:class约束时,请避免使用type参数上的==和!=运算符,因为这些运算符将仅测试引用标识,而不是值相等。 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. 即使String类重载==运算符,输出也是假的。

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);
}

Everything is ok until i tried following, with same method 一切都很好,直到我尝试跟随,用同样的方法

static void Main()
{
    string s1 = "target";
    string s2 = "target";
    OpTest<string>(s1, s2);
}

It outputs 'True', s1 and s2 reference different objects in memory even they have same value right? 它输出'True',s1和s2引用内存中的不同对象,即使它们具有相同的值对吗? Am i missing something? 我错过了什么吗?

Strings are interned in .NET, so when you do 字符串在.NET中实现,所以当你这样做时

string s1 = "target";
string s2 = "target";

they are both pointing to the same object. 他们都指向同一个对象。 This is why the MSDN example uses a StringBuilder , this fools the CLR into creating another string object with the same value so that the operator test in the generic method will return false. 这就是MSDN示例使用StringBuilder ,这使得CLR无法创建具有相同值的另一个字符串对象,因此泛型方法中的运算符测试将返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM