【问题标题】:Passing the correct type parameter to MethodInfo GetMethod将正确的类型参数传递给 MethodInfo GetMethod
【发布时间】:2015-03-06 11:16:44
【问题描述】:

我知道我可以使用question 中的技术来获取我的方法。

例如

MethodInfo firstMethod = typeof(Enumerable)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .First(m => m.Name == "FirstOrDefault" && m.GetParameters().Length == 1)

不过我想缩短这个过程。

我在找Enumerable.FirstOrDefault Method (IEnumerable)

我都试过了

// I'm just using string just as an example.
var enumerableType = typeof(IEnumerable<>).MakeGenericType(typeof(string));
MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", new Type[] { enumerableType });

MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", Type.EmptyTypes);

但两者都返回null

正确的方法是什么?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    不幸的是,当参数类型是泛型时,没有简单的方法来获得正确的重载。您可以手动使用LINQ

    typeof(Enumerable)
      .GetMethods(BindingFlags.Public | BindingFlags.Static)
      .First(x => x.Name == "FirstOrDefault" &&
                  x.GetParameters().Length == 1 &&
                  x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>));
    

    在这种情况下,由于FirstOrDefault 只有一个带有一个参数的重载,您可以删除最后一个条件。但是当存在带有相同数量的不同类型参数的重载时,这是必要的。

    【讨论】:

    • 啊,我知道我错过了那里的支票。不错!
    • 调用GetParameters 两次不是一个好主意,因为它复制了一个用于缓存参数的内部数组。
    • 我可以用匿名函数解决这个问题。感谢您指出。
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多