4

我正在构建一些 Linq 表达式并尝试获取 MethodInfo IEnumerable.DefaultIfEmptyhttp://msdn.microsoft.com/en-us/library/bb360179.aspx)。这似乎是一件容易的事,但我不知道为什么它不起作用。

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

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

1 回答 1

5

老实说,获得通用方法是一件痛苦的事情。我不知道比使用更好的方法:

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

要调用GetMethod,您必须具有完全正确的参数类型,包括参数的正确泛型类型参数。一旦你做到了你就可以做到,但在那之前,我认为以上就是所有可用的:(

于 2011-06-17T09:51:21.360 回答