gpt4 book ai didi

c# - 在泛型函数中使用重载的 operator==

转载 作者:可可西里 更新时间:2023-11-01 08:23:06 25 4
gpt4 key购买 nike

考虑以下代码:

class CustomClass
{
public CustomClass(string value)
{ m_value = value; }

public static bool operator ==(CustomClass a, CustomClass b)
{ return a.m_value == b.m_value; }

public static bool operator !=(CustomClass a, CustomClass b)
{ return a.m_value != b.m_value; }

public override bool Equals(object o)
{ return m_value == (o as CustomClass).m_value; }

public override int GetHashCode()
{ return 0; /* not needed */ }

string m_value;
}

class G
{
public static bool enericFunction1<T>(T a1, T a2) where T : class
{ return a1.Equals(a2); }
public static bool enericFunction2<T>(T a1, T a2) where T : class
{ return a1==a2; }
}

现在,当我调用两个通用函数时,一个成功,一个失败:

var a = new CustomClass("same value");
var b = new CustomClass("same value");
Debug.Assert(G.enericFunction1(a, b)); // Succeeds
Debug.Assert(G.enericFunction2(a, b)); // Fails

显然,G.enericFunction2 执行默认的 operator== 实现而不是我的重写。谁能解释为什么会这样?

最佳答案

来自 Constraints on Type Parameters (C# Programming Guide) :

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 reason for this behavior is that, at compile time, the compiler only knows that T is a reference type, and therefore must use the default operators that are valid for all reference types.

关于c# - 在泛型函数中使用重载的 operator==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2919232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com