2009-05-20 35 views

回答

7

protected

成員只能以繼承類型可見。

protected internal

成員只對繼承的類型和也,它們也含有相同的組件聲明類型中的所有類型可見。

這裏是一個C#示例:

class Program 
{ 
    static void Main() 
    { 
     Foo foo = new Foo(); 

     // Notice I can call this method here because 
     // the Foo type is within the same assembly 
     // and the method is marked as "protected internal". 
     foo.ProtectedInternalMethod(); 

     // The line below does not compile because 
     // I cannot access a "protected" method. 
     foo.ProtectedMethod(); 
    } 
} 

class Foo 
{ 
    // This method is only visible to any type 
    // that inherits from "Foo" 
    protected void ProtectedMethod() { } 

    // This method is visible to any type that inherits 
    // from "Foo" as well as all other types compiled in 
    // this assembly (notably "Program" above). 
    protected internal void ProtectedInternalMethod() { } 
} 
+0

認爲你可能錯過了'內部'的解釋.... – Kev 2009-05-20 17:04:36

+4

確實。它是受保護的或內部的,與首先看起來相反+1 – 2009-05-20 17:07:32

10

私人

訪問只允許從特定類型

保護內

私有接入擴展到包括繼承類型

內部

私有接入擴展到包括其它類型的在同一組件

所以它遵循即:

保護的內部

私有接入被擴展以允許類型要麼繼承或在同一個組件,這種類型的,或兩者的訪問。

基本上,首先想到的一切都是private,還有其他任何你認爲正在擴展的東西。

2

像往常一樣,從Fabulous Eric Lippert's blog posts之一:

許多人認爲[protected internal]手段「M是所有派生類,在本次大會進行訪問。」它不。 它實際上意味着「M可供所有派生類訪問,並且適用於此程序集中的所有類」也就是說,這是限制較少的組合,而不是限制較多的組合。

這對很多人來說都是違反直覺的。我一直在試圖弄清楚爲什麼,我想我已經得到了它。我認爲人們將internal,protectedprivate構想爲來自public的「自然」狀態的限制。使用該模型,protected internal表示「同時應用受保護的限制和內部限制」。

這是錯誤的思考方式。相反,internal,protectedpublicprivate的「自然」狀態的弱化。 private是C#中的默認值;如果你想讓東西有更廣泛的可訪問性,你必須這樣說。有了這個模型,那麼很顯然,protected internal是比單獨一個更弱的限制。

1

protectedprotected internal還是讓我給一個簡單的例子,我將匹配的例子之間的差別...

Country A:一個組件

Country B:彼此不同的組件

X(基類)是父親Y(In herited類)在國家A

Z(繼承的類X)在國家B的X另一個兒子

X有一個屬性。

  1. 如果X提到的財產protected然後 X說:我所有的兒子YZ,只有你都可以訪問我的財產無論你呆在......上帝保佑你。除了你以外,沒有人可以訪問我的財產。

  2. 如果X提到的財產protected internal然後 X說:所有的人在我的國家A包括我的兒子Y,可以訪問我的財產。親愛的兒子Z,仍然可以訪問我的財產Country B

希望你明白傢伙...

謝謝。

相關問題