接口继承与内部基础

Jas*_*per 7 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(); }

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

por*_*ges 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

MethodThatNeedsFruit(banana.AsFruit());
Run Code Online (Sandbox Code Playgroud)

GetName如果名称可能会随着时间的推移而改变,您也可以轻松地将其扩展为对调整后的对象进行懒惰调用.


另一种选择可能是只有一个DEBUG检查,它会加载所有IFruit实现者,然后如果其中一个实际上没有实现IBanana/ 则抛出异常IApple.因为听起来这些类是供公司内部使用的,所以这应该可以阻止任何人意外地执行错误的操作.


Mar*_*k H 2

确实不可能做您正在尝试的事情,但是您可以使用带有[Obsolete]属性的 IFruit 界面来阻止人们,并用消息说明原因。

在 IBanana、IApple 等界面上,禁止显示过时警告。

[Obsolete]
public interface IFruit {
    ...
}

#pragma warning disable 612
public interface IBanana : IFruit {
    ...
}
#pragma warning restore 612
Run Code Online (Sandbox Code Playgroud)