我正在寻找RealProxy
.NET Core 中的替代品,这个问题将我转发到DispatchProxy
.
它有简单的 API,但不清楚如何将现有对象包装到代理中。
例如,有这个接口:
interface IFoo
{
string Bar(int boo);
}
这个实现:
class FooImpl : IFoo
{
public string Bar(int boo)
{
return $"Value {boo} was passed";
}
}
如何得到我想要的?
class Program
{
static void Main(string[] args)
{
var fooInstance = new FooImpl();
var proxy = DispatchProxy.Create<IFoo, FooProxy>();
var s = proxy.Bar(123);
Console.WriteLine(s);
}
}
class FooProxy : DispatchProxy
{
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
return targetMethod.Invoke(/* I need fooInstance here */, args);
}
}
由于DispatchProxy
后代必须有无参数构造函数,我唯一的想法是发明一些方法,如下所示:
class FooProxy : DispatchProxy
{
private object target;
public void SetTarget(object target)
{
this.target = target;
}
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
return targetMethod.Invoke(target, args);
}
}
并以这种方式使用它:
var fooInstance = new FooImpl();
var proxy = DispatchProxy.Create<IFoo, FooProxy>();
((FooProxy)proxy).SetTarget(fooInstance);
// the rest of code...
这是正确的方法吗?