[英]Interface inheritance with an internal base
我想知道是否有办法完成以下任务:
在我的项目中,我定义了一个界面,让我们说IFruit。 此接口具有公共方法GetName()。 我还声明了一个接口IApple,它实现了IFruit并公开了一些其他方法,比如GetAppleType()等。 有更多的水果,如IBanana,ICherry,等等。
现在在外面,我只希望能够使用实际的水果实现而不是IFruit本身。 但是我不能将IFruit接口声明为私有或内部接口,因为继承的接口会说“无法实现,因为基类不易访问”。
我知道这可以通过抽象实现来实现,但在这种情况下这不是一个选项:我真的需要使用接口。 有这样的选择吗?
更新我想我的例子需要一些澄清:)我使用MEF来加载接口实现。 加载的集合基于IApple,IBanana,ICherry等。但IFruit本身是无用的,我不能仅使用基于该接口的类。 所以我一直在寻找一种方法来阻止其他开发人员单独实施IFruit,认为他们的类会被加载(它不会被加载)。 所以基本上,它归结为:
internal interface IFruit
{
public string GetName();
}
public interface IApple : IFruit { public decimal GetDiameter(); }
public interface IBanana : IFruit { public decimal GetLenght(); }
但由于基础接口不易访问,因此无法编译。
一种可以保证这种情况不会无意间发生的方法是让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
。
另一种选择可能是只有一个DEBUG检查, 它会加载所有IFruit
实现者,然后如果其中一个实际上没有实现IBanana
/ IApple
则抛出异常。 因为听起来这些类是供公司内部使用的,所以这应该可以阻止任何人意外地执行错误的操作。
你真的不可能做你正在尝试的事情,但你可以使用带有[Obsolete]
属性的IFruit界面让人们离开,并提供说明原因的消息。
在您的IBanana,IApple,...接口上,禁用显示的过时警告。
[Obsolete]
public interface IFruit {
...
}
#pragma warning disable 612
public interface IBanana : IFruit {
...
}
#pragma warning restore 612
如果你的代码中有一些(假设我正确理解你的状态),就像这样:
public class WaterMellon : IFruit, IVegetables...
{
}
并且你希望能够使你的框架的消费者只访问IFruit
的方法,没有其他已知的方法,然后简单地投射。
IFruit fruit = new WaterMelon();
fruit. //CAN ACCESS ONLY TO FRUIT IMPLEMNTATION AVAILABLE IN WATERMELON
如果这不是您所要求的,请澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.