mardi 29 août 2017

Comparing generic parameter type using reflection

I want to get a method definition that accepts an Action<T> parameter using reflection. I'm using .NET core 1.1.

Since the class has two methods with the same name, I'm trying to check the type of the accepted parameters to make sure that I'm getting the correct method definition (and not the other overload), but the comparison does not seem to work.

Here is some code that shows this problem:

using System;
using System.Linq;
using System.Reflection;

class ReflectMe {
    public void SomeMethod<T>(Action<T> action) {
        action(default(T));
    }
    public T SomeMethod<T>() {
        return default(T);
    }
}

class Program {
    static void Main(string[] args) {
        var reflectedMethod = typeof(ReflectMe).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Instance)
            .Where(m => m.Name == "SomeMethod" && m.IsGenericMethodDefinition)
            .Where(m => {
                var parameters = m.GetParameters();
                if (parameters.Count() != 1) {
                    return false;
                }
                var actionType = typeof(Action<>);
                var parameterType = parameters[0].ParameterType;
                if (parameterType == actionType) { // this is always false
                    return true;
                }
                return false;
            })
            .FirstOrDefault();
    }
}

The problem is that parameterType and actionType are not equal, yet when I check in the debugger they look identical.

Why is that comparison failing?





Aucun commentaire:

Enregistrer un commentaire