禁止类暴露方法

时间:2015-06-05 09:28:51

标签: c# class oop interface

有没有办法禁止某个类暴露某种方法或财产?这有点像接口的反制概念。

示例:

class A : [Somehow prevent to expose method X]
{

}

class B : A 
{
   public void X() // --> Should cause compile error
   {
   }
}

2 个答案:

答案 0 :(得分:3)

如果您不想公开方法或属性,为什么不简单地对该方法或属性使用private访问修饰符?

答案 1 :(得分:1)

问题是模糊的,问题是显式接口实现 n:

  public interface IMyIntf {
    void SomeMethod();
  }

  public class MyClass: IMyIntf {
    ...
    // explicit interface implementation: works as "private"
    // unless cast to the interface
    void IMyIntf.SomeMethod() {
      ...
    }
  }

  ...

  MyClass inst = new MyClass();

  inst.SomeMethod(); // <- compile time error: SomeMethod() is not exposed

  // Only when cast the inst to the interface one can call the method:
  ((IMyIntf) inst).SomeMethod();