我想知道是否有办法完成以下操作:
在我的项目中,我定义了一个接口(interface),假设是 IFruit。该接口(interface)有一个公共(public)方法 GetName()。我还声明了一个 IApple 接口(interface),它实现了 IFruit 并公开了一些其他方法,如 GetAppleType() 或其他方法。还有更多的水果,比如 IBanana、ICherry 等等。
现在在外面,我只想能够使用实际的水果实现,而不是 IFruit 本身。但我不能将 IFruit 接口(interface)声明为私有(private)或内部接口(interface),因为继承的接口(interface)会说“无法实现,因为基类不易访问”。
我知道这可以通过抽象实现实现,但在这种情况下这不是一个选项:我确实需要使用接口(interface)。有这样的选择吗?
更新 我想我的示例需要一些说明 :) 我使用 MEF 来加载接口(interface)实现。加载的集合基于 IApple、IBanana、ICherry 等。但是 IFruit 本身没有用,我不能使用仅基于该接口(interface)的类。所以我正在寻找一种方法来防止其他开发人员单独实现 IFruit,认为他们的类将被加载(它不会)。所以基本上,它归结为:
internal interface IFruit
{
public string GetName();
}<p></p>
<p>public interface IApple : IFruit
{
public decimal GetDiameter();
}</p>
<p>public interface IBanana : IFruit
{
public decimal GetLenght();
}</p>
但由于基础接口(interface)的可访问性较低,因此无法编译。
最佳答案
可以保证这不会无意中发生的一种方法是将 IFruit
internal
放入程序集,然后使用一些适配器适本地包装类型:
public interface IApple { string GetName(); }
public interface IBanana { string GetName(); }
internal interface IFruit { string GetName(); }
class FruitAdaptor: IFruit
{
public FruitAdaptor(string name) { this.name = name; }
private string name;
public string GetName() { return name; }
}
// convenience methods for fruit:
static class IFruitExtensions
{
public static IFruit AsFruit(this IBanana banana)
{
return new FruitAdaptor(banana.GetName());
}
public static IFruit AsFruit(this IApple apple)
{
return new FruitAdaptor(apple.GetName());
}
}
然后:
MethodThatNeedsFruit(banana.AsFruit());
如果名称会随着时间的推移发生变化,您还可以轻松地扩展它以延迟调用适配对象上的 GetName
。
另一种选择可能是进行仅调试检查是否加载所有IFruit
实现,然后如果其中一个没有实际实现则抛出异常IBanana
/IApple
。由于这些类听起来像是供贵公司内部使用的,因此这应该可以防止任何人意外实现错误的事情。
关于c# - 具有内部基础的接口(interface)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795782/