创建一个Action<'T>的实例使用反射

编程入门 行业动态 更新时间:2024-10-10 06:15:19
本文介绍了创建一个Action<'T>的实例使用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用反射创建一个 Action 的实例?这是我有的:

How would I create an instance of Action<'T> using reflection? Here's what I have:

let makeAction (typ:Type) (f:'T -> unit) = let actionType = typedefof<Action<_>>.MakeGenericType(typ) let converter = FSharpFunc.ToConverter(f) Delegate.CreateDelegate(actionType, converter.Method)

哪些barfs与:

系统.ArgumentException:绑定到目标方法的错误。 在System.Delegate.CreateDelegate(Type type,MethodInfo method,Boolean throwOnBindFailure)

System.ArgumentException: Error binding to target method. at System.Delegate.CreateDelegate(Type type, MethodInfo method, Boolean throwOnBindFailure)

'T 是一个接口, typ implements。

'T is an interface, which typ implements.

推荐答案

我认为有两个问题。第一个是你需要调用 CreateDelegate 重载,它需要三个参数。附加参数指定应该调用该方法的实例。

I think there are two problems. The first one is that you need to call CreateDelegate overload that takes three arguments. The additional argument specifies the instance on which the method should be invoked.

第二个问题是 Converter<'T,unit> code>实际编译为返回 Microsoft.FSharp.Core.Unit 的方法,而不是返回 void 。我不确定是否有更容易的解决方法,但您可以定义一个包含方法的包装器。会员被编译成C#,所以在这种情况下,单元类型将被编译为 void :

The second problem is that the Converter<'T, unit> actually compiles as a method that returns Microsoft.FSharp.Core.Unit and not a method that returns void. I'm not sure if there is an easier workaround, but you can define a wrapper that has a method. Members are compiled to look like C#, so the unit type will be compiled as void in that case:

open System type Wrapper<'T>(f:'T -> unit) = member x.Invoke(a:'T) = f a let makeAction (typ:Type) (f:'T -> unit) = let actionType = typedefof<Action<_>>.MakeGenericType(typ) let wrapperType = typedefof<Wrapper<_>>.MakeGenericType(typ) let wrapped = Wrapper<_>(f) Delegate.CreateDelegate(actionType, wrapped, wrapped.GetType().GetMethod("Invoke")) makeAction (typeof<int>) (printfn "%d")

编辑 - 稍微改动,使其在您的场景中实际工作(使用界面)

EDIT - Did a minor change to make it actually work in your scenario (with interface)

更多推荐

创建一个Action&lt;'T&gt;的实例使用反射

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

发布评论

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

>www.elefans.com

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