从程序集中提取特定IL(.NET中间语言)签名的机制

时间:2010-09-01 23:09:40

标签: .net reflection il intermediate-language

我有一个在Microsoft .NET程序集mscorlib.dll中找到的大约25种类型的列表,我需要提取该类及其成员的IL签名。我想要每种类型一个文件,每个签名在一行上。因此,例如,采取类型

System.Collections.Generic.Comparer<T>

我想从该类型的程序集中提取以下内容(我不需要一些私有成员,但如果需要,我可以手动处理)。

.class public abstract auto ansi serializable beforefieldinit System.Collections.Generic.Comparer`1<T> extends System.Object implements System.Collections.IComparer, class System.Collections.Generic.IComparer`1<!T>
.method family hidebysig specialname rtspecialname instance void  .ctor() cil managed
.method public hidebysig newslot abstract virtual instance int32  Compare(!T x, !T y) cil managed
.method private hidebysig newslot virtual final instance int32  System.Collections.IComparer.Compare(object x, object y) cil managed
.property class System.Collections.Generic.Comparer`1<!T> Default() { .get class System.Collections.Generic.Comparer`1<!T> System.Collections.Generic.Comparer`1::get_Default() }

所以,我想到了实现这个目标的四种方法:

  • 手动将每种类型的每个签名剪切并粘贴到ildasm的文本文件中(直接或通过mscorlib.dll转储)。有些类型很长,所以这可能会很乏味。如果我需要做更多的事情,这绝对不是一个好的长期解决方案。

  • 编写一个使用Reflection来尝试获取所有签名的工具。我在高层次上考虑使用类似下面的伪代码[1]。

  • 编写一个工具,在ildasm的IL转储上使用字符串解析来查找类型并获取签名

  • 使用现有工具完成任务。

有没有人知道可以帮助我完成任务的现有工具或机制?如果没有,有关建立这样一个工具的方向的建议吗?如果您有关于如何完成任务的任何代码想法,我将不胜感激。

[1]

System.Reflection.GetType(string)
Type.GetMethods() For each item in
MethodInfo, GetMethodBody()
GetILAsByteArray().ToString()
Determine a way to get just the signature from the IL

3 个答案:

答案 0 :(得分:2)

您可以从MethodInfo中找到的信息重建方法签名。你不需要GetMethodBody - 那里没有签名信息。 MemberInfo.Name,MemberInfo.ReturnType,MemberInfo.GetParameters()等等就在那里。

答案 1 :(得分:1)

红色反射镜可以使切割和粘贴更快。

答案 2 :(得分:1)

如果您决定从IL获取签名,则需要编写某种签名解析器。 David Broman在MSDN代码库here上发布了一个样本。它没有完全正常运行(具体来说,你必须添加对泛型的支持),但它确实为你提供了一个良好的开端。