Question

I wonder since there is no way how to implement a generic Decorator class in C# (is it?) like this:

public class Decorator<TDecoratorIterface> : TDecoratorInterface 
{
    public TDecoratorInterface Component {get; private set;}

    protected Decorator(TDecoratorInterface component)
    {
        Component = component;
    }
}

use like this:

public interface IDogDecorator 
{
    void Bark();
}

public class Dog : IDogDecorator
{
    public void Bark()
    {
        Console.Write("I am a dog");
    }
}

public class StinkingDog : Decorator<IDogDecorator>
{
    public StinkingDog(IDogDecorator dog):base(dog)
    {
    }

    public void Bark()
    {
        Component.Bark();
        Console.WriteLine(" and I stink");
    }
}

can such a thing be managed via PostSharp or any other AOP framework for .NET?

thank fro your answers, I spent half a day trying to create such a construct without any success, so any help is appreciatted:)

Était-ce utile?

La solution

There's no direct equivalent to this construct, as C# doesn't allow the base class of a type to be dynamic. Remember that the generic type must be fully defined at compile time, not at usage time.

There's multiple possible ways to go: In the example above, the StinkingDog should just implement the IDogDecorator interface. So just specify that there. You're forwarding calls anyway.

public class StinkingDog : Decorator<IDogDecorator>, IDogDecorator

There would probably be frameworks that do what you want exactly (i.e. Rhino.Mocks is actually creating Mocks this way), but for production code, I'd really suggest not doing any AOP approach. It's clumsy and slow.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top