我有以下代码。我需要隐藏界面的一项功能。
interface IOne
{
int FunctionOne();
}
interface ITwo
{
double FunctionTwo();
}
interface IInterfaceToImplement : IOne, ITwo
{
void AFunctionToImplement();
}
public abstract MyBaseClass : TheVeryHeavyBaseClass<T, IInterfaceToImplement>, IInterfaceToImplement
{
public abstract void AFunctionToImplement(); // How to force this one to be protected?
public virtual int FunctionOne() { return 0; }
public virtual double FunctionTwo() { return 0.0; }
}
public MyConcreteClass : MyBaseClass
{
public override void AFunctionToImplement(); // How to force this one to be protected?
}
正如你所看到的,我有基类。我需要隐藏 AFunctionToImplement() 。我的类(class)设计很糟糕吗?关于如何保护函数不被调用有什么建议吗?
编辑。回答评论中帕维尔·米纳耶夫的问题。
我需要每个具体类实现 IInterfaceToImplement 中的函数列表。另外,我需要每个具体类都能够存储 IInterfaceToImplement 类型的类。 这是树状数据存储。存储的每个“分支”都必须执行与任何其他分支相同的操作。但除了“根”和其他“分支”之外,没有其他人必须调用这些操作。
编辑2我的解决方案。
感谢马修·阿博特和帕维尔·米纳耶夫。我终于意识到我的问题了——是大脑。 :)
不,我是在开玩笑。 :) 问题是 - 我认为根类和分支类属于同一分支。现在我明白了 - 根不应该实现 IInterfaceToImplement 。查看解决方案:
public class MyRootClass : IOne, ITwo
{
private IInterfaceToImplement internalData = new MyConcreteClass();
public int FunctionOne() { return this.internalData.FunctionOne(); }
public double FunctionTwo() { return this.internalData.FunctionTwo(); }
}
最佳答案
我建议使用显式接口(interface)实现:
void IInterfaceToImplement.AFunctionToImplement();
...但这不允许您在子类中公开和实现该方法,并且仍然隐藏它。在这种情况下,您可能需要重新考虑您的类设计。
你最好的选择,如下所示:
public interface IMyInterface
{
void DoWork();
}
public abstract class MyInterfaceBase : IMyInterface
{
/// <summary>
/// Forced implementation.
/// </summary>
protected abstract void DoWork();
/// <summary>
/// Explicit implementation.
/// </summary>
void IMyInterface.DoWork()
{
// Explicit work here.
this.DoWork();
}
}
如果从 IMyInterface 引用而不是 MyInterfaceBase 引用调用该方法,这仍然会留下 DoWork 公开暴露的问题。你根本无法绕过这个。如果我执行以下操作:
MyInterface first = new MyInterface(); // Let's assume I have implemented MyInterface : MyInterfaceBase
first.DoWork(); // Compile error, can't access method here.
鉴于:
IMyInterface second = new MyInterface();
second.DoWork(); // No problem.
你能看到问题吗?
关于c# - 部分 protected 接口(interface)但没有抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177753/