如果“流畅”使用,则成员无法受到保护,即使它不应在外部使用

问题描述

我有以下示例:

class A {
    public A DoSomethingInternal() {
        // Some work..
        return this;
    }
}

class B : A {
    public void DoSomething() {
        DoSomethingInternal().DoSomethingInternal().DoSomethingInternal();
    }
}

DoSomethingInternal 是一种不应被外部对象调用方法。它应该只能被 AA 的继承者访问 - 所以它听起来应该是 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();
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...