如果使用 "fluently",成员将无法受到保护,即使它不应在外部使用
Member can't be protected if used "fluently", even though it shouldn't be used outside
我有以下例子:
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();
}
}
但我发现要求派生 类 进行这些转换非常不雅。
您可以“告诉”基础 class 关于派生 class 作为泛型类型参数。
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();
}
}
我有以下例子:
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();
}
}
但我发现要求派生 类 进行这些转换非常不雅。
您可以“告诉”基础 class 关于派生 class 作为泛型类型参数。
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();
}
}