如何获取 GenericInstanceType 的方法?
How to get the methods of a GenericInstanceType?
open System
open System.Runtime.CompilerServices
open Mono.Cecil
open Mono.Cecil.Rocks
type SpiralType =
| IntT
| StringT
| TupleT of SpiralType list
let module_ = ModuleDefinition.CreateModule("TypeTokenFactory",ModuleKind.Console)
let r1 = module_.ImportReference(typeof<obj>)
let r2 = module_.ImportReference(typeof<obj>)
let table = ConditionalWeakTable()
table.Add(r1,IntT)
table.Add(r2,StringT)
let mscorlib_path = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
let mscorlib = AssemblyDefinition.ReadAssembly(mscorlib_path)
let dictionary_type =
mscorlib.Modules.[0].Types
|> Seq.find (fun x -> x.Name = "Dictionary`2")
let dict_ins = dictionary_type.MakeGenericInstanceType([|r1;r2|])
// Lacks the Methods field...
长期以来,我一直在尝试弄清楚如何使上述功能与 System.Type
一起使用,但现在我正在尝试与 Mono.Cecil
一起使用。有关我正在尝试做的事情的一些历史,请看一下我在 F# 存储库上打开的最后一个 two questions here on SO and the issue,它深入探讨了它。
让我在这里简短地总结一下:为了与我正在制作的语言集成,我需要能够查询 .NET 程序集的类型并为两者替换通用参数 类 和方法。
现在,我不需要替换确切的类型。如上面的示例所示,将元数据附加到虚拟类型对于我的目的来说已经足够了,但现在我遇到了与 System.Type
不同的问题,一旦我替换了通用参数,我就无法再查询类型上的方法。
这么近。有什么方法可以使 Mono.Cecil
正常工作吗?或者,我很想知道是否可以使用其他一些库。为了我的目的,我根本不需要 Cecil 的程序集编辑能力。
Cecil 为您提供了相对较低级别的元数据视图。
Cecil 将为您提供在程序集中表示不同元数据构造的方法,但不会提供类型的运行时表示。
为了回答您的问题,它不会告诉您实例化泛型类型的方法,因为这是运行时构造,无法从元数据中获得。
更高级别的 API,如 System.Reflection 或 IKVM.Reflection 将执行此操作。
open System
open System.Runtime.CompilerServices
open Mono.Cecil
open Mono.Cecil.Rocks
type SpiralType =
| IntT
| StringT
| TupleT of SpiralType list
let module_ = ModuleDefinition.CreateModule("TypeTokenFactory",ModuleKind.Console)
let r1 = module_.ImportReference(typeof<obj>)
let r2 = module_.ImportReference(typeof<obj>)
let table = ConditionalWeakTable()
table.Add(r1,IntT)
table.Add(r2,StringT)
let mscorlib_path = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
let mscorlib = AssemblyDefinition.ReadAssembly(mscorlib_path)
let dictionary_type =
mscorlib.Modules.[0].Types
|> Seq.find (fun x -> x.Name = "Dictionary`2")
let dict_ins = dictionary_type.MakeGenericInstanceType([|r1;r2|])
// Lacks the Methods field...
长期以来,我一直在尝试弄清楚如何使上述功能与 System.Type
一起使用,但现在我正在尝试与 Mono.Cecil
一起使用。有关我正在尝试做的事情的一些历史,请看一下我在 F# 存储库上打开的最后一个 two questions here on SO and the issue,它深入探讨了它。
让我在这里简短地总结一下:为了与我正在制作的语言集成,我需要能够查询 .NET 程序集的类型并为两者替换通用参数 类 和方法。
现在,我不需要替换确切的类型。如上面的示例所示,将元数据附加到虚拟类型对于我的目的来说已经足够了,但现在我遇到了与 System.Type
不同的问题,一旦我替换了通用参数,我就无法再查询类型上的方法。
这么近。有什么方法可以使 Mono.Cecil
正常工作吗?或者,我很想知道是否可以使用其他一些库。为了我的目的,我根本不需要 Cecil 的程序集编辑能力。
Cecil 为您提供了相对较低级别的元数据视图。
Cecil 将为您提供在程序集中表示不同元数据构造的方法,但不会提供类型的运行时表示。
为了回答您的问题,它不会告诉您实例化泛型类型的方法,因为这是运行时构造,无法从元数据中获得。
更高级别的 API,如 System.Reflection 或 IKVM.Reflection 将执行此操作。