How to hide the entire class?

2019-08-04 02:16发布

问题:

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();

回答1:

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.



回答2:

Type forwarding can help: Type Forwarding in the Common Language Runtime