为什么"等于"泛型方法解析从显式调用不同 [英] Why "Equals" method resolution with generics differs from explicit calls

查看:152
本文介绍了为什么"等于"泛型方法解析从显式调用不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的例子:

namespace ComparisonExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var hello1 = new Hello();
            var hello2 = new Hello();

            // calls Hello.Equals
            var compareExplicitly = hello1.Equals(hello2);

            // calls Object.Equals
            var compareWithGenerics = ObjectsEqual<Hello>(hello1, hello2); 
        }

        private static bool ObjectsEqual<TValue>(TValue value1, TValue value2)
        {
            return value1.Equals(value2);
        }
    }

    class Hello : IEquatable<Hello>
    {
        public bool Equals(Hello other)
        {
            return true; // doesn't matter
        }
    }
}



问题是,为什么在第二个等于叫我重定向到的Object.Equals,而不是即使我指定在一般的参数的确切类型Hello.Equals?

The question is why in the second "Equals" call I'm redirected to Object.Equals instead of Hello.Equals even though I'm specifying the exact type in generic argument?

推荐答案

由于你还没有告诉泛型方法,你的对象实现 IEquatable< T>

Because you haven't told the generic method that your object implements IEquatable<T>:

现在有尝试:

private static bool ObjectsEqual<TValue>(TValue value1, TValue value2) 
               where TValue : IEquatable<TValue> // IMPORTANT!!!
{
    return value1.Equals(value2);
}

在你的 ObjectsEqual 方法你只有方法/在对象中定义的属性/ TValue 字段访问类加的方法在约束定义的接口/基类中定义。无约束=>你只有等于(对象),的GetHashCode()的GetType(),(如果你有约束运算符== 运算符!= )。这两个都是虚的(等于(对象)的GetHashCode( )),所以你用正确的版本,第三个没有正常覆盖(的GetType()),所以你'可能会使用正确的版本。只有两家运营商 == / != 往往覆盖,你瞧!在您的泛型方法,你不能使用两个正确的版本! : - )

In your ObjectsEqual method you have access only to methods/properties/fields of TValue that are defined in the object class plus the methods that are defined in the interfaces/base classes defined in the constraints. No constraints => you have access only to Equals(object), GetHashCode(), GetType(), (and if you have the constraint class: operator==, operator!=.) Of these two are virtual (Equals(object), GetHashCode()), so you'll use the "correct" version, the third isn't normally overwritten (GetType()), so you'll probably use the "correct" version. Only the two operators ==/!= are often overwritten and lo and behold! In your generic method you can't use the "correct" version of the two! :-)

这篇关于为什么&QUOT;等于&QUOT;泛型方法解析从显式调用不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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