5

我正在尝试使用 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属性MethodReference为空,因此GenericParameters[0]给出ArgumentOutOfRangeException. 我已经探索了MethodReference,并且肯定会收到对 的调用,但是除了没有用的属性Farm::Add之外,我看不到与正在使用的泛型类型相关的任何地方。FullName

如何让 Cecil 识别调用中使用的泛型类型?

4

1 回答 1

3

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

var callsInError = testCases
    .Where(test => !((GenericInstanceMethod)test).GenericArguments[0].Resolve().IsClass)
    ;
于 2013-06-12T21:19:38.473 回答