简体   繁体   English

运算符使用泛型函数参数重载

[英]Operator overloading with generic function parameters

I have a problem with operator resolution on generic methods. 我对泛型方法的运算符解析有问题。

From my understanding of section 7.3.4 of the spec within the function EqualOperatorGeneric (sample code below) the correct overload of the == operator on the type A should be found, but instead it seems to get the candidate for (object, object). 根据我对函数EqualOperatorGeneric中规范7.3.4节的理解(下面的示例代码),应该找到类型A上的==运算符的正确重载,但它似乎得到(对象,对象)的候选者。

Am I doing something very obvious wrong? 我做了一件非常明显错误的事吗? Is there a method to get the expected behaviour and if not can I turn the given case into a compile time or runtime error? 有没有一种方法可以获得预期的行为,如果没有,我可以将给定的情况转换为编译时或运行时错误吗?

public class A
{
    public A(int num)
    {
        this.Value = num;
    }

    public int Value { get; private set; }

    public override bool Equals(object obj)
    {
        var other = obj as A;
        if (Object.ReferenceEquals(other, null))
            return false;

        return Object.Equals(this.Value, other.Value);
    }

    public override int GetHashCode()
    {
        return this.Value.GetHashCode();
    }

    public static bool operator ==(A l, A r)
    {
        if (Object.ReferenceEquals(l, null))
        {
            return !Object.ReferenceEquals(r, null);
        }

        return l.Equals(r);
    }

    public static bool operator !=(A l, A r)
    {
        return !(l == r);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(EqualOperatorGeneric(new A(1), new A(1)));
    }

    public static bool EqualOperatorGeneric<L, R>(L l, R r)
        where L : class
        where R : class
    {
        return l == r;
    }
}

Output: 输出:

False

When EqualOperatorGeneric is compiled the == operator needs to be bound statically, when the method is compiled, to a single implementation. 编译EqualOperatorGeneric==运算符需要在编译方法时静态绑定到单个实现。 It is not bound separately for each separate usage of the generic method. 对于通用方法的每个单独使用,它不单独绑定。

This is what differentiates generics from, say, C++ templates. 这就是将泛型与C ++模板区分开来的原因。 The generic method is compiled once and then applied to every usage with every set of type arguments, whereas templates are compiled separately for each set of generic arguments. 泛型方法编译一次 ,然后应用于每个类型参数集的每个用法,而模板则为每组泛型参数单独编译。

After scrounging the spec I realized you can use the dynamic keyword to defer binding of the operator from compile time to runtime. 在浏览规范之后,我意识到您可以使用dynamic关键字将运算符的绑定从编译时延迟到运行时。 This fixes the issues I have been having: 这解决了我一直遇到的问题:

public static bool EqualOperatorGeneric<L, R>(L l, R r)
{
    dynamic dl = l, dr = r;
    return dl == dr;
}

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

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