Dictionary 如何在FSharp中从反射调用Map.Add?

Dictionary 如何在FSharp中从反射调用Map.Add?,dictionary,reflection,f#,Dictionary,Reflection,F#,在FSI中给出以下代码: type Mapping = Map<int,string> let mm = [ for i in Assembly.GetAssembly(typeof<Mapping>).ExportedTypes do yield i]|> List.find(fun m -> m.Name.Contains("MapModule")) let mt = mm.GetMethod("Empty", BindingFlags.Static |

在FSI中给出以下代码:

type Mapping = Map<int,string>

let mm = [ for i in Assembly.GetAssembly(typeof<Mapping>).ExportedTypes do yield i]|> List.find(fun m -> m.Name.Contains("MapModule"))
let mt = mm.GetMethod("Empty", BindingFlags.Static ||| BindingFlags.Public)
let mymap = mt.MakeGenericMethod([|typeof<string>; typeof<string>|]).Invoke(null, [||])

let addmethod = typeof<Mapping>.GetMethod("Add")

addmethod.Invoke(mymap, [|box(1);box("astring")|])
那么,如何从反射中有效地调用Map.Add呢?

找到了它

这一行:

let mymap = mt.MakeGenericMethod([|typeof<string>; typeof<string>|]).Invoke(null, [||])
让mymap=mt.MakeGenericMethod([| typeof;typeof |]]).Invoke(null,[| |]]
应该是:

let mymap = mt.MakeGenericMethod([|typeof<int>; typeof<string>|]).Invoke(null, [||])
让mymap=mt.MakeGenericMethod([| typeof;typeof |]]).Invoke(null,[| |]]
类型不匹配实际上是真实的,因为使用不正确的泛型类型调用了“Empty”方法

这就是最终正确的代码:

type Mapping = Map<int,string>

let mm = [ for i in Assembly.GetAssembly(typeof<Mapping>).ExportedTypes do yield i]|> List.find(fun m -> m.Name.Contains("MapModule"))
let mt = mm.GetMethod("Empty", BindingFlags.Static ||| BindingFlags.Public)
let am = mm.GetMethod("Add", BindingFlags.Static ||| BindingFlags.Public)
let mymap = mt.MakeGenericMethod([|typeof<int>; typeof<string>|]).Invoke(null, [||])
let addmethod = typeof<Mapping>.GetMethod("Add")

addmethod.Invoke(mymap, [|box(1);box("astring")|])
类型映射=映射
让mm=[对于Assembly.GetAssembly(typeof).ExportedTypes中的i产生i]|>List.find(fun m->m.Name.Contains(“MapModule”))
设mt=mm.GetMethod(“空”,BindingFlags.Static | | | BindingFlags.Public)
设am=mm.GetMethod(“Add”,BindingFlags.Static | | | BindingFlags.Public)
让mymap=mt.MakeGenericMethod([| typeof;typeof |]]).Invoke(null,[| |]]
让addmethod=typeof.GetMethod(“Add”)
调用(mymap,[| box(1);box(“astring”)|])

我猜
Map
中的
int
没有被框在F类型中,这是您的问题的原因,因为
1
box 1
不是同一类型(一个是
int
,另一个是
obj
),有什么建议吗?这也不起作用:
addmethod.Invoke(mymap,[| 1;“astring”|])
,这也不起作用:
addmethod.Invoke(mymap,[| 1:>obj;“astring:”)
type Mapping = Map<int,string>

let mm = [ for i in Assembly.GetAssembly(typeof<Mapping>).ExportedTypes do yield i]|> List.find(fun m -> m.Name.Contains("MapModule"))
let mt = mm.GetMethod("Empty", BindingFlags.Static ||| BindingFlags.Public)
let am = mm.GetMethod("Add", BindingFlags.Static ||| BindingFlags.Public)
let mymap = mt.MakeGenericMethod([|typeof<int>; typeof<string>|]).Invoke(null, [||])
let addmethod = typeof<Mapping>.GetMethod("Add")

addmethod.Invoke(mymap, [|box(1);box("astring")|])