【问题标题】:Generic equality implementation for derived classes派生类的通用相等实现
【发布时间】:2018-04-28 07:18:35
【问题描述】:

我希望派生特定类 A 的对象也以某种方式派生 Equals(A other) 的实现,这将执行以下操作:如果 thisother 的类型不同,则返回 false,否则返回 this.value == other.value .

我的尝试如下所示:

public class A<T> : IEquatable<A<T>>
    where T: A<T>
{
    protected string Value { get; }
    public A(string value)
    {
        Value = value;
    }

    public bool Equals(A<T> other)
    {
        var concrete = other as T;
        if (concrete == null)
        {
            return false;
        }

        return concrete.Value == Value;
    }
}

public class B : A<B>
{
    public B(string value)
        : base(value)
    {

    }
}

public class C : A<C>
{
    public C(string value)
        : base(value)
    {

    }
}

class Program
{
    static void Main(string[] args)
    {
        var b1 = new B("val");
        var b2 = new B("val");
        var c = new C("val");

        Console.WriteLine(b1.Equals(b1));
        Console.WriteLine(b1.Equals(b2));
        Console.WriteLine(b2.Equals(b1));
        Console.WriteLine(b1.Equals(c));
        Console.WriteLine(b2.Equals(c));
        Console.WriteLine(c.Equals(b1));
        Console.WriteLine(c.Equals(b2));
    }
}

在我们得到更多信息之前,这可以正常工作:

public class D : C
{
    public D(string value)
        : base(value)
    {

    }
}

然后它就坏了:

        var d = new D("val");
        Console.WriteLine(d.Equals(c)); // prints "True"

现在我被困住了。我如何使它工作? 修复实现以使用多级继承和防止多级继承都是可以接受的。

虽然我明白我只需将A&lt;T&gt; 的所有第一级后代声明为已密封,但这是最后的手段,除非它可以以某种方式强制执行(因此A&lt;T&gt; 的非密封后代会导致编译错误)。 还是我的方法完全错误?

【问题讨论】:

    标签: c# generics equality


    【解决方案1】:

    这都是因为as 运算符可以毫无问题地将子类转换为超类。

    您要做的是检查类型并查看它们是否相等:

    if (this.GetType() == other.GetType()) {
        return false;
    }
    

    这个question有点相关,关于GetTypetypeofis的行为,其作用类似于as

    【讨论】:

    • 我怀疑我想多了。这可行,但我会在接受之前等待其他答案。
    • 那么A类就不用泛型了。
    • @DannyChen 从 OP 显示的内容来看,A 根本不需要是通用的,但这不可能是 OP 的完整代码,所以我假设 OP 在其他地方使用了通用参数.
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多