基本结构:
public abstract class Base<T> where T : Base<T>
{
public T Original { get; private set; }
public abstract bool Changed(T o);
public bool Changed()
{
return this.Changed(Original);
}
}
public class DerivedA : Base<DerivedA>
{
public override bool Changed(DerivedA o)
{
throw new NotImplementedException();
}
}
public class DerivedB : Base<DerivedB>
{
public override bool Changed(DerivedB o)
{
throw new NotImplementedException();
}
}
虽然它有其缺点(可读性),但在这种情况下它可能是正确的选择,因为您的问题不是经典动物/狗/猫意义上的类型保护,而是代码共享。
为了防止这种情况:
public class DerivedC : DerivedB
{
}
new DerivedB().Changed(new DerivedC()); // compiles
你可以密封DerivedB
。
或者你可以继续疯狂(我不推荐这个。绝对不会超过这个水平):
public abstract class DerivedE<T> : Base<DerivedE<T>> where T : DerivedE<T>
{
}
public class DerivedF : DerivedE<DerivedF>
{
}
public class DerivedG : DerivedE<DerivedG>
{
}
new DerivedF().Changed(new DerivedG()); // does not compile
new DerivedF().Changed(new DerivedF()); // does compile
请参阅此http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx。我从那篇文章中得到了灵感。他讨论了利弊。
编辑:清理,根据评论调整