公共抽象类中实现内部接口的抽象方法不能编译?

Dan*_*iel 3 c# inheritance

internal interface I_Foo
{
    void Bar();
}

public abstract class A_Foo : I_Foo
{
    public A_Foo() { }
    abstract void I_Foo.Bar();
}

public class Foo : A_Foo
{
    public Foo() : base() { }
    internal override void Bar()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

你好!我试图让一些方法对外部代码可见,而其他方法只对我的程序集可见.为此,我提出,实施A_Foo和I_Foo内部接口I_Foo作为合同到组件的其他部分,公共抽象A_Foo作为抽象为外部代码,并集中了一些构造函数的功能,和几个不同类别的Foo明确保留内部修饰符.

但是,在A_Foo类中,我得到了

'A_Foo.I_Foo.Bar()'必须声明一个正文,因为它没有标记为abstract,extern或partial

即使该方法明确标记为"抽象".如果我添加一个正文,我会得到"抽象不是一个有效的修饰符".

我需要显式声明这个方法,以便在公共类中内部,我需要它是抽象的,所以我可以在实际的实现Foo中覆盖它.

为什么编译器不允许我?还有另一种方法可以达到同样的目的吗?谢谢.

Jon*_*eet 11

显式接口实现总是必须具有实际的实现.这里的诀窍是让它只调用一个非显式(内部)抽象方法:

public abstract class A_Foo : I_Foo
{
    // Classes outside the assembly can't derive from A_Foo
    // anyway, so let's make the constructor internal...
    internal A_Foo() { }

    void I_Foo.Bar()
    {
        Bar(); // Just delegate to the abstract method
    }

    internal abstract void Bar();
}
Run Code Online (Sandbox Code Playgroud)

这仍然允许I_Foo使用内部类型等,因为Bar它永远不会公开 - 但它符合该语言的其他规则.