接口继承与内部基础

时间:2012-05-29 08:41:42

标签: c# inheritance interface

我想知道是否有办法完成以下任务:

在我的项目中,我定义了一个界面,让我们说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(); }

但由于基础接口不易访问,因此无法编译。

3 个答案:

答案 0 :(得分:6)

一种可以保证不会发生这种情况的方法是无意中将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实现者​​,然后如果其中一个实际上没有实现{{1}则抛出异常} / IBanana。因为听起来这些类是供公司内部使用的,所以这应该可以阻止任何人意外地执行错误的操作。

答案 1 :(得分:2)

你真的不可能做你正在尝试的事情,但你可以使用带有[Obsolete]属性的IFruit界面让人们离开,并留言说明原因。

在您的IBanana,IApple,...界面上,禁用显示的过时警告。

[Obsolete]
public interface IFruit {
    ...
}

#pragma warning disable 612
public interface IBanana : IFruit {
    ...
}
#pragma warning restore 612

答案 2 :(得分:0)

如果你的代码中有一些(假设我正确理解你的状态),就像这样:

public class WaterMellon : IFruit, IVegetables...
{
}

并且您希望能够让您的框架消费者访问IFruit的方法,没有其他已知的方法,然后简单地投射。

IFruit fruit = new WaterMelon();
fruit. //CAN ACCESS ONLY TO FRUIT IMPLEMNTATION AVAILABLE IN WATERMELON

如果这不是您所要求的,请澄清。