【问题标题】:Mono.Cecil : Get generic parameter nameMono.Cecil : 获取通用参数名称
【发布时间】:2019-12-12 01:39:09
【问题描述】:

我们正在编写一个项目来检查我们的 nuget 包中是否存在引用问题。因此我们决定使用 Mono.cecil 来提取每个方法调用,然后检查是否找到适合该调用的方法。

在提取每个方法调用时,我得到例如

string fullName = !!0 Extensions::MinBy(System.Collections.Generic.IEnumerable`1<!!0>,System.Func`2<!!0,!!1>)

其中 !!0 和 !!1 是该方法的泛型参数:

public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> selector)

我想知道是否有办法代替:

TSource Extensions::MinBy(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource, TKey>)
                AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(path);
                foreach (ModuleDefinition module in assembly.Modules)
                {
                    foreach (TypeDefinition type in module.Types)
                    {
                        foreach (MethodDefinition method in type.Methods.Where(x => x.HasBody))
                        {
                            foreach (var il in method.Body.Instructions)
                            {
                                if (il.OpCode == OpCodes.Call || il.OpCode == OpCodes.Calli || il.OpCode == OpCodes.Callvirt)
                                {
                                    var mRef = il.Operand as MethodReference;

                                    string fullName = mRef.GetElementMethod().FullName; // This is where i get !!0 Extensions::MinBy(System.Collections.Generic.IEnumerable`1<!!0>,System.Func`2<!!0,!!1>)

                                    **//TODO : Find a way to obtain parameters names**

                                }
                            }
                        }
                    }
                }

非常感谢

【问题讨论】:

    标签: c# reflection mono.cecil


    【解决方案1】:

    我不确定 Mono.Cecil 是否提供此功能。来自声明类型的类型参数似乎使用类型参数名称(而不是 IL 语法 !0、!1 等)。

    话虽如此,您可以执行以下操作(请记住,这只是为了获得灵感):

    var genMethod = mRef as GenericInstanceMethod;
    if (genMethod != null)
    {
        for(var i = 0 ; i < genMethod.GenericArguments.Count; i++)
            fullName = fullName.Replace($"!!{i}",  genMethod.GenericArguments[i].Name);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 2016-10-21
      • 2020-08-19
      相关资源
      最近更新 更多