如何使用Cecil查找传递给泛型方法的类型?

时间:2013-06-12 09:21:54

标签: c# cil mono.cecil

我正在尝试使用Cecil来查找使用常规测试接口的泛型方法调用的实例。我无法从MethodReference确定通用类型。

我已经设置了基本测试:

private interface IAnimal
{
}

private class Duck : IAnimal
{
}

private class Farm
{
    private readonly ICollection<string> _animals = new List<string>();

    public void Add<T>()
    {
        _animals.Add(typeof(T).Name);
    }

    public override string ToString()
    {
        return string.Join(", ", _animals);
    }
}

static Farm FarmFactory()
{
    var farm = new Farm();
    farm.Add<Duck>();
    farm.Add<Duck>();
    farm.Add<IAnimal>();    // whoops
    farm.Add<Duck>();
    return farm;
}

private static void Main(string[] args)
{
    var farm = FarmFactory();
    Console.WriteLine("Farm:");
    Console.WriteLine(farm);

    // Use Cecil to find the call to farm.Add<IAnimal>():
    Console.WriteLine("Errors:");
    FindErrors();
    Console.Read();
}

所以我想找到对farm.Add<IAnimal>()的调用,它不会产生编译时错误甚至是运行时错误,直到该场可以想象通过反射创建该类型的实例。我的实际用例是DI容器的常规测试。

塞西尔用FindErrors()方法进入它:

private static void FindErrors()
{
    var methods = AssemblyDefinition.ReadAssembly(typeof (Farm).Assembly.Location)
                                    .Modules
                                    .SelectMany(module => module.Types)
                                    .SelectMany(type => type.Methods)
                                    .Where(method => method.HasBody)
                                    .ToArray()
        ;
    var callsToFarmDotAdd = methods
        .Select(method => new
            {
                Name = method.Name,
                MethodReferences = GetCallsToFarmDotAdd(method)
            })
        .Where(x => x.MethodReferences.Any())
        .ToArray()
        ;
    var testCases = callsToFarmDotAdd
        .SelectMany(x => x.MethodReferences)
        ;
    var callsInError = testCases
        .Where(test => !test.GenericParameters[0].Resolve().IsClass)
        ;

    foreach (var error in callsInError)
    {
        Console.WriteLine(error.FullName);
    }
}

private static IEnumerable<MethodReference> GetCallsToFarmDotAdd(MethodDefinition method)
{
    return method.Body.Instructions
                 .Where(instruction => instruction.OpCode == OpCodes.Callvirt)
                 .Select(instruction => (MethodReference) instruction.Operand)
                 .Where(methodReference => methodReference.FullName.Contains("Farm::Add"))
        ;
}

callsInError部分是我无法识别调用Farm::Add时使用的泛型类型的地方。具体来说,GenericParameters的{​​{1}}属性为空,因此MethodReference会提供GenericParameters[0]。我已经探索了ArgumentOutOfRangeException,我肯定会接到MethodReference的调用,但除了Farm::Add属性之外,我无法看到与使用的泛型类型有关的任何地方,这没用。

如何让Cecil识别通话中使用的通用类型?

1 个答案:

答案 0 :(得分:3)

如果我将MethodReference转换为GenericInstanceMethodGenericArguments参数可以满足我的需求:

var callsInError = testCases
    .Where(test => !((GenericInstanceMethod)test).GenericArguments[0].Resolve().IsClass)
    ;