在一个通用的函数重载使用==操作符 [英] Using overloaded operator== in a generic function

查看:106
本文介绍了在一个通用的函数重载使用==操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码:

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

现在,当我打电话都通用的功能,一个人成功了一失败

Now when I call both generic functions, one succeeds and one fails:

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执行默认的==操作符的实现,而不是我的覆盖。任何人都可以解释为什么出现这种情况?

Apparently, G.enericFunction2 executes the default operator== implementation instead of my override. Can anybody explain why this happens?

推荐答案

从的类型参数的约束(C#编程指南)

在应用其中T :类约束,避免了==和=的类型参数运营商,因为这些运营商将测试参考身份而已,不是值相等!这是即使这些运算符在于使用作为参数类型超载的情况。 (......)这样做的原因行为是,在编译时,编译器只知道T是引用类型,因此必须使用默认运算符适用于所有引用类型。

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.

这篇关于在一个通用的函数重载使用==操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆