我收到錯誤消息:擴(kuò)展方法必須在非通用靜態(tài)類中定義在線上:public class LinqHelper這是基于Mark Gavells代碼的幫助程序類。我對這個錯誤的含義感到非常困惑,因為我確信當(dāng)我在星期五離開它時,它可以正常工作!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);
3 回答

嚕嚕噠
TA貢獻(xiàn)1784條經(jīng)驗 獲得超7個贊
更改
public class LinqHelper
至
public static class LinqHelper
創(chuàng)建擴(kuò)展方法時,需要考慮以下幾點:
其限定一個擴(kuò)展方法必須是類non-generic,static和non-nested
每個擴(kuò)展方法都必須是一個static方法
擴(kuò)展方法的第一個參數(shù)應(yīng)使用this關(guān)鍵字。

PIPIONE
TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
static在類聲明中添加關(guān)鍵字:
// this is a non-generic static class
public static class LinqHelper
{
}
- 3 回答
- 0 關(guān)注
- 843 瀏覽
添加回答
舉報
0/150
提交
取消