2014-02-08 178 views
1

我想要完成與here所描述的完全相同的操作,但在C#中。用受保護的方法裝飾類

public interface IFoo { void DoSomething(); } 

public class Foo : IFoo 
{ 
    public void DoSomething() {...} 
    protected void Bar() {...} 
} 

public class Foo2 : IFoo 
{ 
    private readonly Foo _foo; 

    public Foo2 (Foo foo) { _foo = foo; } 

    public void DoSomething() {...} 

    protected void Bar() 
    { 
     _foo.Bar(); // cannot access Bar() from here 
    } 
} 

我看了幾個類似的問題,但他們都沒有真正告訴你如何解決這個問題。試圖用受保護的方法來裝飾一個類首先要做的錯誤事情?

+0

約'protected'整個想法是,它僅在訪問當前類和它的子類。在Java和C#中,您將永遠無法在只持有引用的類中訪問它。 –

+0

相關問題http://stackoverflow.com/a/614844/682480 –

回答

5

受保護的方法只對子類可見。如果FooFoo2在同一個組件可以使Foo.Bar內部而非:

public class Foo 
{ 
    internal void Bar() { ... } 
} 
+0

謝謝,這似乎是一個合理的方法。 – CookieMonster

0

唯一的區別是protected方法可以用在派生類中而private方法不能。所以這不是一個正確或錯誤的問題,而是它是否需要該功能的問題。

See this SO answer for more clarification

0

您可以將中級班FooInternal:

public interface IFoo { void DoSomething(); } 

public class Foo : IFoo 
{ 
    public void DoSomething() {} 
    protected void Bar() {} 
} 

public class FooInternal : Foo 
{ 
    internal void Bar() 
    { 
     base.Bar(); 
    } 
} 

public class Foo2 : IFoo 
{ 
    private readonly FooInternal _foo; 

    public Foo2(FooInternal foo) { _foo = foo; } 

    public void DoSomething() {} 

    protected void Bar() 
    { 
     _foo.Bar(); // can access Bar() from here 
    } 
} 
+0

但是,您正在將Bar作爲公共方法。 – CookieMonster

+0

按@Lee建議你可能會使這個方法成爲內部的。我已經更新了我的答案。 – neodim