2015-06-05 147 views
-5

有什么办法禁止类暴露某种方法或属性?这有点像接口的计数器概念。禁止类暴露方法

例子:

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

} 

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

我想有像私有的,封闭! –

+0

@ubaid gadha:'private'不能被继承,所以'sealed'是多余的 –

+4

请显示一些示例代码来说明你的问题,因为它不清楚你要问什么。你的意思是你想标记一个像_这样的类,“这个类永远不会暴露'字符串Foo()'方法,并且它必须是编译时错误。也解释你为什么想要这样的事情。 – CodeCaster

回答

3

如果你不希望公开的方法或属性,为什么不直接使用该方法或属性的private访问修饰符?

+3

并从界面中删除它 –

1

的问题是一个模糊一个,听起来显式接口实现The 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();