IQueryable 扩展方法不起作用

我如何制作一个像这样工作的扩展方法

public static class Extensions { public static IQueryable Sort(this IQueryable query, string sortField, SortDirection direction) { // System.Type dataSourceType = query.GetType(); //System.Type dataItemType = typeof(object); //if (dataSourceType.HasElementType) //{ // dataItemType = dataSourceType.GetElementType(); //} //else if (dataSourceType.IsGenericType) //{ // dataItemType = dataSourceType.GetGenericArguments()[0]; //} //var fieldType = dataItemType.GetProperty(sortField); if (direction == SortDirection.Ascending) return query.OrderBy(s => s.GetType().GetProperty(sortField)); return query.OrderByDescending(s => s.GetType().GetProperty(sortField)); } } 

目前说“扩展方法必须在非generics静态类中定义”。

我该怎么做呢?

试试这个……(但我不确定它会做你想要的。)

 public static class Extensions { public static IQueryable Sort(this IQueryable query, string sortField, SortDirection direction) { if (direction == SortDirection.Ascending) return query.OrderBy(s => s.GetType() .GetProperty(sortField)); return query.OrderByDescending(s => s.GetType() .GetProperty(sortField)); } } 

…generics参数应该在方法上,而不是在类上。 将它从Extensions移动到Sort(将允许您摆脱您遇到的编译器错误。

至于你想用reflection做什么,你将返回orderby子句的PropertyInfo对象。 这很可能与您想要的表达式树不兼容。 您可能想看看Dynamic LINQ

…这是Dynamic LINQ的摘录。

 public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (ordering == null) throw new ArgumentNullException("ordering"); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(source.ElementType, "") }; ExpressionParser parser = new ExpressionParser(parameters, ordering, values); IEnumerable orderings = parser.ParseOrdering(); Expression queryExpr = source.Expression; string methodAsc = "OrderBy"; string methodDesc = "OrderByDescending"; foreach (DynamicOrdering o in orderings) { queryExpr = Expression.Call( typeof(Queryable), o.Ascending ? methodAsc : methodDesc, new Type[] { source.ElementType, o.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters))); methodAsc = "ThenBy"; methodDesc = "ThenByDescending"; } return source.Provider.CreateQuery(queryExpr); } 

改变这个:

 public static class Extensions { public static IQueryable Sort(this IQueryable query, string sortField, SortDirection direction) { //code } } 

该类需要是非generics的,只需要你的扩展方法:)

错误已经告诉你:

必须在非generics静态类中定义扩展方法。

只需删除generics类型参数即可。

 public static class Extensions // no  { // ... }