我得到的錯誤定義擴展方法必須在非泛型靜態類
public class LinqHelper
這裏是輔助類的基礎上,馬克Gavells碼。我真的很困惑這個錯誤是什麼意思,因爲我確信當我在星期五離開時它工作的很好!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Helper methods for link
/// </summary>
public class LinqHelper
{
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IOrderedQueryable<T>)result;
}
}
另外添加*非嵌套*在第一點。 – nawfal 2013-06-02 07:16:51
如果您已將該類放入App_Code中,那麼它肯定會在類定義中使用static關鍵字,但如果將其放在任何其他文件夾中,則可以將其用作普通類。 – 2014-09-09 06:58:16
在一個案例中,我曾使用'public static class IQueryable where T:MyBaseClass' which which also generate this error。 'where T:MyBaseClass'短語屬於靜態類上沒有''的單個方法。 –
2016-02-11 19:09:14