2011-06-17 48 views
4

我正在構建一些Linq表達式並試圖獲取IEnumerable.DefaultIfEmptyhttp://msdn.microsoft.com/en-us/library/bb360179.aspx)的MethodInfo。什麼似乎是一件容易的事,但我無能爲力,爲什麼它不工作。獲取Enumerable.DefaultIfEmpty的方法信息

typeof(Enumerable).GetMethod("DefaultIfEmpty", new[] { typeof(IEnumerable<>) }); 

typeof(Enumerable).GetMethod("DefaultIfEmpty", new[] { typeof(IEnumerable<>).MakeGenericType(typeof(WorkitemListModel)) }); 
+0

相關,但不是一個笨蛋:http://stackoverflow.com/questions/3631547/select -right-generic-method-with-reflection/3632196#3632196 – LukeH

+0

@LukeH這是一個有趣的解決方案。:) –

回答

5

獲得通用方法是一個痛苦,說實話。我不知道的,而不是用一種更好的方式:

var method = typeof(Enumerable).GetMethods() 
           .Where(m => m.Name == "DefaultIfEmpty") 
           .Where(m => m.GetParameters().Length == 1) 
           .Single(); 

要調用GetMethod,你必須有確切的參數類型,包括參數正確泛型類型參數。一旦你得到了一次你可以做到這一點,但在此之前,我認爲上述是所有可用的:(