如何将现有对象实例包装到DispatchProxy中?

编程入门 行业动态 更新时间:2024-10-06 18:20:37
本文介绍了如何将现有对象实例包装到DispatchProxy中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找.NET Core中的 RealProxy 替代品,并且此问题将我转发到 DispatchProxy 。

I'm looking for RealProxy replacement in .NET Core, and this issue forwards me to DispatchProxy.

它具有简单的API,但尚不清楚如何将现有的 对象包装到其中代理。 例如,具有以下接口:

It has simple API, but it's unclear, how to wrap existing object into proxy. E.g., having this interface:

interface IFoo { string Bar(int boo); }

以及此实现:

class FooImpl : IFoo { public string Bar(int boo) { return $"Value {boo} was passed"; } }

如何获得我想要的东西?

how to get what I want?

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 后代必须具有无参数构造函数,我唯一的想法就是发明一些方法,例如:

Since DispatchProxy descendants must have parameterless constructor, the only idea I have is to invent some method, like this:

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...

这是正确的方法吗?

推荐答案

您是正确的,这里除了投射生成的 IFoo之外没有其他选择转换为已知的代理类型( FooProxy ),并在 FooProxy 上使用自定义方法或属性。没有公共API可添加构造函数参数或将代理返回为实现类型。但是, DispatchProxy.Create()将返回 FooProxy 的子类的实例,该子类的类型在运行时通过反射生成

You are right that there is no other option here than to cast the generated IFoo to the known proxy type (FooProxy) and use a custom method or property on FooProxy. There is no public API to add constructor arguments or return the proxy as the implementation type. However, DispatchProxy.Create() will return an instance of a subclass of FooProxy whose type is generated at runtime via reflection and IL emitting.

如果您正在寻找其他快速包装实现并替换接口方法/虚拟方法的方法,建议您改用模拟框架(FakeItEasy,Moq, NSubstitute等。)

If you are looking at other ways to quickly wrap an implementation and replace interface methods / virtual methods, I suggest using mocking frameworks instead (FakeItEasy, Moq, NSubstitute etc.).

更多推荐

如何将现有对象实例包装到DispatchProxy中?

本文发布于:2023-11-26 19:09:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634830.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   实例   对象   DispatchProxy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!