2011-06-17 51 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,你必须有确切的参数类型,包括参数正确泛型类型参数。一旦你得到了一次你可以做到这一点,但在此之前,我认为上述是所有可用的:(