C#Multiple Interface Inheritance不允许具有相同名称的公共访问修饰符

joh*_*y 5 2 c# encapsulation interface access-modifiers multiple-inheritance

所以这让我感到困惑.
假设有两个接口.

public interface a
{
    void foo();
}

public interface b
{
    void foo();
}
Run Code Online (Sandbox Code Playgroud)

这两个接口都有一个函数foo,我有一个提供显式实现的类:

public class alpha : a, b
{
    // why can't I put an access modifier here?
    // How would you be able to hide this from a derived class
    void a.foo()
    {
        Console.WriteLine("a");
    }

   void b.foo()
    {
        Console.WriteLine("b");
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个派生自alpha的类

public class beta : alpha
{
}
Run Code Online (Sandbox Code Playgroud)

你如何使foo私有或受保护,因为alpha不允许在显式的imlementation上访问修饰符,什么可以阻止某人调用:

var be = new beta();
(be as b).foo();
Run Code Online (Sandbox Code Playgroud)

编辑

为什么我没有明确提供实现我可以提供访问修饰符?

public class alpha : a, b
{
   //why this compile? 
   public void foo()
    {
        Console.WriteLine("both");
    }

}
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 8

由于接口a是公共的,因此任何实现的类a必须a隐式(通过公共方法)或显式地使公共方法可公开访问.显式实现是"排序"私有的,因为它们只能通过接口访问.

简而言之,没有办法完全"隐藏" foo- 你的类实现了两者a,b所以这些方法必须通过某种方式使我可以访问.

即使您只有一个接口,这也是正确的- 具有方法名称冲突的多个接口只会强制您使实现显式化.如果您有一个接口,foo则必须是public显式的.

  • 您可以提供访问修饰符,但必须是"public".如果接口是`public`,则隐式实现必须是`public`.除了`public`之外,你不能使`foo`成为任何东西,或者你违反了接口合同. (2认同)

Jam*_*iec 6

什么可以阻止某人打电话

没什么,这就是重点!

beta是一个b,因此你可以把它当作一个b.如果您选择将其强制转换b并调用显式foo实现,您将获得b实现.

  • 选择1 - `public`. (3认同)