[英]Generic equality implementation for derived classes
我希望派生某些类A
对象也以某种方式派生Equals(A other)
的实现,该实现将执行以下操作:如果this
和other
类型不同,则返回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<T>
所有第一级后代为已密封,但这是最后的选择,除非可以通过某种方式强制执行(这样, A<T>
未密封后代会导致编译错误)。 还是我的方法完全错误?
这是因为as
运算符可以毫无问题地将子类转换为超类。
您要做的是检查类型,看它们是否相等:
if (this.GetType() == other.GetType()) {
return false;
}
这个问题是样的关系,有关行为GetType
, typeof
和is
,它的工作原理类似于as
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.