Reputation: 715
I'm looking for a way to create a generic wrapper for any object.
The wrapper object will behave just like the class it wraps, but will be able to have more properties, variable, methods etc., for e.g. object counting, caching etc.
Say the wrapper class be called Wrapper, and the class to be wrapped be called Square and has the constructor Square(double edge_len) and the properties/methods EdgeLength and Area, I would like to use it as follows:
Wrapper<Square> mySquare = new Wrapper<Square>(2.5); /* or */ new Square(2.5);
Console.Write("Edge {0} -> Area {1}", mySquare.EdgeLength, mySquare.Area);
Obviously I can create such a wrapper class for each class I want to wrap, but I'm looking for a general solution, i.e. Wrapper<T>
which can handle both primitive and compound types (although in my current situation I would be happy with just wrapping my own classes).
Suggestions?
Thanks.
Upvotes: 6
Views: 11664
Reputation: 48949
DynamicProxy from the Castle project might be the solution for you.
Upvotes: 3
Reputation: 1032
Maybe something like this:
public class Wrapper<T>
{
public readonly T Object;
public Wrapper(T t)
{
Object = t;
}
}
And then you could use it as follows:
Wrapper<Square> mySquare = new Wrapper<Square>(new Square(2.5));
Console.Write("Edge {0} -> Area {1}", mySquare.Object.EdgeLength, mySquare.Object.Area);
Upvotes: 2