Dictionary 如何在FSharp中从反射调用Map.Add?
在FSI中给出以下代码: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 |
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")|])