2016-05-12 31 views
3

泛型方法我有一个类查找静态类

public static class MyClass 
{ 

    public static T MyMethod<T>(T item) where T : ISomeInterface<T>, new 
    { 
     return MyMethod(new[] { item}).First(); 
    } 

    public static IEnumerable<T> MyMethod<T>(params T[] items) where T : ISomeInterface<T>, new 
    { 
     // for simplicity 
     return items.ToList(); 
    } 
} 

和一帮更为复杂的过载。 现在我想用

public static IEnumerable MyMethod(string typeName, params object[] items) 
    { 
     var type = Type.GetType(typeName, true, true); 
     var paramTypes = new Type[] { type.MakeArrayType() }; 
     var method = typeof(MyClass).GetMethod(
      "MyMethod", BindingFlags.Public | BindingFlags.Static 
       | BindingFlags.IgnoreCase, null, paramTypes, null); 
     return method.Invoke(null, new object[] { items }); 
    } 

method扩展类(因为我想,如果从PowerShell来调用)始终为空。这是通过GetMethod()获得我的特定方法的正确方法。

+1

什么是'table'变量?你的意思是'typeName'吗? –

+0

这些方法是实例方法还是静态方法? –

+0

'不能在静态类中声明实例成员'。 –

回答

2

我不认为你可以使用GetMethod搜索一个通用的方法(我不知道,但)。但是,您可以使用GetMethods让所有方法,然后过滤它们是这样的:

var method = typeof (MyClass) 
    .GetMethods(
     BindingFlags.Public | BindingFlags.Static) 
    .Single(x => x.Name == "MyMethod" 
     && x.IsGenericMethod 
     && x.ReturnType == typeof(IEnumerable<>) 
          .MakeGenericType(x.GetGenericArguments()[0])); 

请注意,最后一个条件是检查,该方法的返回类型是IEnumerable<T>让我们没有得到方法返回T

请注意,您可以将method变量缓存为静态变量,这样您就不必每次都搜索它。

请注意,返回的方法仍然是打开的(它仍然是MyMethod<T>)。您仍然需要通过这样的方法调用MakeGenericMethod创建一个封闭的版本:

var closed_method = method.MakeGenericMethod(type); 

然后,您可以调用它像这样:

return (IEnumerable)closed_method.Invoke(null, new object[] { items }); 
+0

我建议使用LINQ Single方法而不是First,尤其是在像这样的反射环境中。 – thehennyy

+0

@thehennyy,对。如果有多个方法具有相同的标准,我们希望失败。 –