问题描述
我有以下示例:
class A {
public A DoSomethingInternal() {
// Some work..
return this;
}
}
class B : A {
public void DoSomething() {
DoSomethingInternal().DoSomethingInternal().DoSomethingInternal();
}
}
DoSomethingInternal
是一种不应被外部对象调用的方法。它应该只能被 A
和 A
的继承者访问 - 所以它听起来应该是 protected
。
但是,由于 DoSomethingInternal
是一种“流畅”的方法,我无法使它protected
。
我看到的解决方案是:
class A {
public A DoSomethingInternal() {
// Some work..
return this;
}
}
class B : A {
public void DoSomething() {
((B)(((B)DoSomethingInternal()).DoSomethingInternal())).DoSomethingInternal();
}
}
但我发现要求派生类进行这些转换非常不雅。
解决方法
您可以将派生类作为泛型类型参数“告诉”基类。
public abstract class A<T> where T : A<T>
{
protected T DoSomethingInternal()
{
// Do something
return (T)this;
}
}
public class B : A<B>
{
public void DoSomething()
{
// Do something
this.DoSomethingInternal().DoSomethingInternal();
}
}