How to hide the entire class?

2019-08-04 01:56发布

Lets imagine:

// assembly 01

abstract class Foo
{
    abstract void Bar();
}
class AdvancedFoo : Foo
{
    override void Bar() { base.Foo(); ... }
}
sealed class SuperiorFoo : AdvancedFoo
{
    override sealed void Bar() { base.Foo(); }
}

And then I want to reference that assembly 01 from my 02 asm and replace the intermediate base class (and only it) so the instances of a SuperiorFoo were acting like they are inhereting from assembly 02's AdvancedFoo.

// assembly 02

class AdvancedFoo : Foo
{
    override void Bar() { base.Foo(); ... }
}

Is there any way to do that by not rewriting the SuperiorFoo class declaration if the 02 assembly?

var supFoo = new SuperiorFoo();
supFoo.Bar(); // This one should call assembly 02's Bar();

2条回答
我只想做你的唯一
2楼-- · 2019-08-04 02:18

Not in the way that you are doing no, but you could possibly use composition rather than inheritance to solve your issue:

interface IFoo
{
    abstract void Bar();
}
class AdvancedFoo : IFoo
{
    override void Bar() { base.Foo(); ... }
}
sealed class SuperiorFoo : IFoo
{
    private IFoo _fooImplementer;

    public SuperiorFoo()
    {
        _fooImplemnter = new AbstractFoo();
    }

    public SuperiorFoo(IFoo fooImplementer)
    {
       _fooImplementer = fooImplementer;
    }

    void Bar() { _fooImplementer.Foo(); }
}

To call from your second assembly, you would use the second constructor, passing an instance of your new 'advancedfoo' class.

查看更多
太酷不给撩
3楼-- · 2019-08-04 02:26
登录 后发表回答