c# - 从非泛型静态类中的泛型重载方法获取 RuntimeMethodInfo

标签 c# system.reflection methodinfo

我尝试在静态类中获取运行时方法信息。我在类中有四个静态方法,每个名称都相等,参数名称也相等。唯一的区别是它们的类型。四种方法之一具有字符串参数,因此很容易获取方法信息。然而其他人不工作。我找到了一些建议,但不起作用。

所有测试代码都在这里。

class Program {
    static void Main(string[] args) {
        //ok
        var stringMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(string) });
        //not working
        var dictMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(Dictionary<,>) });
        //not working
        var genericMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(object) });
        //not working
        var listMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(List<>) });


        //not working
        var res = typeof(TestClass)
        .GetRuntimeMethods()
        .Where(x => x.Name.Equals("TestMethod"))
        .Select(m => new { Method = m, Parameters = m.GetParameters() })
        .FirstOrDefault(p =>
            p.Parameters.Length == 1
        && p.Parameters[0].ParameterType.IsGenericType
        && p.Parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(ICollection<>)
        );

    }
}


public static class TestClass {
    public static bool TestMethod(string item) {
        return true;
    }

    public static bool TestMethod<TKey, TValue>(Dictionary<TKey, TValue> item) {
        return true;
    }

    public static bool TestMethod<T>(T item) {
        return true;
    }

    public static bool TestMethod<T>(List<T> item) {
        return true;
    }
}

最佳答案

如果您使用的是 .net core 2.1 或更高版本,则可以使用 Type.MakeGenericMethodParameter 来引用方法的泛型参数。您可以使用它来创建与 GetMethod 一起使用的泛型类型参数(不适用于 GetRuntimeMethod)。

var stringMethodInfo = typeof(TestClass).GetRuntimeMethod("TestMethod", new[] { typeof(string) });
Type[] dictionaryTypeParameters = { typeof(Dictionary<,>).MakeGenericType(Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(1)) };
MethodInfo dictMethodInfo = typeof(TestClass).GetMethod("TestMethod", 2, dictionaryTypeParameters);
MethodInfo listMethodInfo = typeof(TestClass).GetMethod("TestMethod", 1, new[] { typeof(List<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) });
MethodInfo genericMethodInfo = typeof(TestClass).GetMethod("TestMethod", 1, new[] { Type.MakeGenericMethodParameter(0) });

关于该主题的一些有趣的读物here .

关于c# - 从非泛型静态类中的泛型重载方法获取 RuntimeMethodInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65871040/

相关文章:

c# - 为什么 ICustomAttributeProvider.GetCustomAttributes() 返回 object[] 而不是 Attribute[]?

c# - 反射(reflection):如何在 C# 7.0 中查找和调​​用本地函数?

c# - Unity3d AudioClip用AudioSource播放无法正常工作

c# - 如何将 List<X> 转换为 Dictionary<X,Y> 并用 null 填充值?

c# - 通过反射获取对象

c# - 如何通过反射找到重载的方法

C# - 如何获取 MethodInfo 的实例?

c# - 为什么.NET中_MethodInfo接口(interface)不叫IMethodInfo?

c# - 如何配置两个JSON序列化器并根据路由选择正确的一个

c# - 如何通过静态类或其他方式更改密封类方法?