代码之家  ›  专栏  ›  技术社区  ›  Bastien Vandamme

您无法在方法或接口中定义访问修饰符是有原因的吗?

  •  5
  • Bastien Vandamme  · 技术社区  · 16 年前

    public interface IMyInterface
    {
      bool GetMyInfo(string request);
    }
    

    在C#中,在方法GetMyInfo()生成以下错误之前,设置访问修饰符public、private或protected:修饰符“private”对此项无效。

    您无法在方法或接口中定义访问修饰符是有原因的吗?

    here )

    5 回复  |  直到 16 年前
        1
  •  14
  •   GraemeF    16 年前

        2
  •  10
  •   Fredrik Mörk    16 年前

    如果你做了一个显式的接口实现,那么实际上在实现类中将该方法设置为私有:

    public interface IMyInterface
    {
        bool GetMyInfo(string request);
    }
    
    public class MyClass : IMyInterface
    {
        public void SomePublicMethod() { }
    
        bool IMyInterface.GetMyInfo(string request)
        {
            // implementation goes here
        }
    }
    

    GetMyInfo MyClass 实例到 IMyInterface :

    MyClass instance = new MyClass();
    
    // this does not compile
    bool result = instance.GetMyInfo("some request"); 
    
    // this works well on the other hand
    bool result = ((IMyInterface)instance).GetMyInfo("some request");
    

    因此,在接口的上下文中,其所有成员都是公开的。它们可以隐藏在实现类的公共接口中,但总是有可能对实例进行类型转换并以此方式访问成员。

        3
  •  4
  •   Wim    16 年前

        4
  •  1
  •   chriseyre2000    16 年前

        5
  •  0
  •   Matt Breckon    16 年前

    1. 约束实现类必须实现方法或属性
    2. 用实施细节混淆界面的概念性质