我需要在C#中创建一个动态代理。 我希望这个类能够包装另一个类,并承担它的公共接口,转发对这些函数的调用:
class MyRootClass
{
public virtual void Foo()
{
Console.Out.WriteLine("Foo!");
}
}
interface ISecondaryInterface
{
void Bar();
}
class Wrapper<T> : ISecondaryInterface where T: MyRootClass
{
public Wrapper(T otherObj)
{
}
public void Bar()
{
Console.Out.WriteLine("Bar!");
}
}
这是我想要使用它的方式:
Wrapper<MyRootClass> wrappedObj = new Wrapper<MyRootClass>(new MyRootClass());
wrappedObj.Bar();
wrappedObj.Foo();
生产:
Bar!
Foo!
有什么想法吗?
最简单的方法是什么?
最好的方法是什么?
非常感谢。
更新
我尝试遵循Wernight的建议,使用C#4.0动态代理来实现这一点。不幸的是,我还是卡住了。代理的重点是模拟期望的其他接口(通常情况下)。使用DynamicObject需要我更改所有此类客户端以使用“dynamic”而不是“ISecondaryInterface”。
是否有一种方法可以获得代理对象,使其在包装A时静态地支持A的接口;并且当它包装B时,宣传它支持B的接口?
更新2
例如:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}