【发布时间】:2011-06-03 14:50:06
【问题描述】:
我需要在 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 需要我将它的所有客户端更改为使用“动态”而不是“ISecondaryInterface”。
有没有办法获得一个代理对象,这样当它包装一个 A 时,它(静态地?)宣传它支持 A 的接口;当它包装一个B时,它会宣传支持B的接口?
更新 2
例如:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}
【问题讨论】:
-
你怎么会得到这样的东西来编译? Wrapper 没有 Foo 方法....
标签: c# .net .net-3.5 dynamic-programming dynamic-proxy