2016-05-12 41 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,對。如果有多個方法具有相同的標準,我們希望失敗。 –