基本结构:
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();
}
}
虽然它有其阴谋(reability),但在这种情况下可能是正确的选择,因为在古典动物/Dog/Cat意义上,你的问题不是类型保护,而是代码共享。
为防止出现这种情况:
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” rel=“nofollow”。我从文章中得到灵感,他讨论了阴谋和主张。
EDIT:清洁清洁,根据评论调整