2014-02-08 127 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