简体   繁体   English

F# 反射:将数组作为参数传递给 MethodInfo.Invoke

[英]F# Reflection : Passing an Array as Argument to MethodInfo.Invoke

In a previous post I was shown how to use F# Reflection to get keys from a single boxed Map object, Map<'k,'v> , at runtime.在上一篇博文中,我展示了如何在运行时使用 F# 反射从单个装箱 Map 对象Map<'k,'v>获取键。 I tried to extend the idea and pass an array of boxed Map objects, Map<'k,'v>[] , but I cannot find a way to extend the original single-object approach to take an array of objects as argument.我试图扩展这个想法并传递一个装箱 Map 对象数组Map<'k,'v>[] ,但我找不到一种方法来扩展原始的单对象方法以将对象数组作为参数。 I came up with a solution which works but doesn't look right.我想出了一个有效但看起来不对的解决方案。 I am looking for a better, more idiomatic way.我正在寻找一种更好、更惯用的方式。

In the code below, keysFromMap gets an array of keys from a single boxed Map<'k,'v> argument;在下面的代码中, keysFromMap从单个装箱Map<'k,'v>参数中获取一个键数组; keysFromMapArray is my first attempt to do the same from a boxed Map<'k,'v>[] argument - but it does not work - and keysFromMapArrayWithCast does work, but having to do the downcast at the FromMapArrayWithCast getter level does not seem right. keysFromMapArray是我第一次尝试从盒装Map<'k,'v>[]参数中做同样的事情 - 但它不起作用 - keysFromMapArrayWithCast确实有效,但必须在 FromMapArrayWithCast getter 级别进行向下转换似乎不正确.

The error message I get from running keysFromMapArray (test2 commented out) :我从运行 keysFromMapArray 得到的错误消息(test2 注释掉了):

{System.ArgumentException: Object of type 'System.Object[]' cannot be converted to type 'Microsoft.FSharp.Collections.FSharpMap`2[System.String,System.Int32][]'.

My question : why extending the keysFromMap approach to take an array of Maps argument does not work, and how to fix it so that it does?我的问题:为什么扩展 keysFromMap 方法以采用 Maps 参数数组不起作用,以及如何修复它以使其起作用?

Example code:示例代码:

module Example = 
    open System

    let foo1 = [| ("foo11", 11); ("foo12", 12) |] |> Map.ofArray
    let foo2 = [| ("foo21", 21); ("foo22", 22) |] |> Map.ofArray

    type KeyGetter = 
        static member FromMap<'K, 'V when 'K : comparison>(map:Map<'K, 'V>) = 
            [| for kvp in map -> kvp.Key |]

        static member FromMapArray<'K, 'V when 'K : comparison>(maps:Map<'K, 'V>[]) = 
            maps |> Array.map (fun mp -> [| for kvp in mp -> kvp.Key |]) |> Array.concat

        static member FromMapArrayWithCast<'K, 'V when 'K : comparison>(omaps:obj[]) = 
            let typedmaps = [| for omp in omaps -> omp :?> Map<'K, 'V> |]  // -- DOWNCASTING HERE --
            typedmaps |> Array.map (fun mp -> [| for kvp in mp -> kvp.Key |]) |> Array.concat

    let keysFromMap (oMap : obj) : obj[] =
        let otype = oMap.GetType()    
        match otype.Name with
        | "FSharpMap`2" ->          
            typeof<KeyGetter>.GetMethod("FromMap")
                .MakeGenericMethod(otype.GetGenericArguments())
                .Invoke(null, [| box oMap |]) :?> obj[]
        | _             ->  
            Array.empty

    let keysFromMapArray (oMaps : obj[]) : obj[] =
        // skipped : tests to check that oMaps is not empty, and that all elements have the same type...
        let otype = oMaps.[0].GetType()    
        match otype.Name with
        | "FSharpMap`2" ->          

            typeof<KeyGetter>.GetMethod("FromMapArray")
                .MakeGenericMethod(otype.GetGenericArguments())
                .Invoke(null, [| box oMaps |]) :?> obj[] // -- FAILS HERE --
        | _             ->  
            Array.empty

    let keysFromMapArrayWithCast (oMaps : obj[]) : obj[] =
        // skipped : tests to check that oMaps is not empty, and that all elements have the same type...
        let otype = oMaps.[0].GetType()    
        match otype.Name with
        | "FSharpMap`2" ->          

            typeof<KeyGetter>.GetMethod("FromMapArrayWithCast")
                .MakeGenericMethod(otype.GetGenericArguments())
                .Invoke(null, [| box oMaps |]) :?> obj[]
        | _             ->  
            Array.empty

    [<EntryPoint>]
    let main argv =
        printfn "#test1: keys from Map<'k,'v> - works"
        let test = keysFromMap foo1

        // printfn "#test2: keysFromArray from Map<'k,'v>[] - FAILS"
        // let test = keysFromMapArray [| foo1; foo2 |]

        printfn "#test3: keysFromArrayWithCast from obj[] - works"
        let test = keysFromMapArrayWithCast [| foo1; foo2 |]

        Console.ReadKey() |> ignore
        0 // return exit code 0

This is the same case as the following:这与以下情况相同:

> type K = static member F(x:int[]) = 3
let f x = typeof<K>.GetMethod("F").Invoke(null, [|(x:obj[])|])
f [|2; 3|];;
System.ArgumentException: Object of type 'System.Object[]' cannot be converted to type 'System.Int32[]'.
   at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at <StartupCode$FSI_0002>.$FSI_0002.main@()
Stopped due to error

Making the intermediate function generic solves the problem.使中间函数泛型解决了这个问题。

> type K = static member F(x:int[]) = 3
let f x = typeof<K>.GetMethod("F").Invoke(null, [|(x:'a[])|]) // unconstrained!
f [|2; 3|];;
type K =
  class
    static member F : x:int [] -> int
  end
val f : x:'a [] -> obj
val it : obj = 3

This can be applied to keysFromMapArray .这可以应用于keysFromMapArray

    let keysFromMapArray (oMaps : 'a[]) : obj[] =

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM