2015-06-05 146 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();