本文介绍了扩展方法必须在非泛型静态类中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到错误:
在行上:
public class LinqHelper
这里是基于Mark Gavells代码的助手类。我真的很困惑,这个错误的意思,因为我相信它工作正常,当我离开星期五!
Here is the helper class, based on Mark Gavells code. I'm really confused as to what this error means as I am sure it was working fine when I left it on Friday!
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;
}
}
推荐答案
change
public class LinqHelper
到
public static class LinqHelper
创建扩展方法时需要考虑以下几点:
Following points need to be considered when creating an extension method:
- 定义扩展方法必须
非泛型
,static
和非嵌套
- 每个扩展方法必须是
static
方法 - 扩展方法的第一个参数应该使用
this
关键字。
- The class which defines an extension method must be
non-generic
,static
andnon-nested
- Every extension method must be a
static
method - The first parameter of the extension method should use the
this
keyword.
这篇关于扩展方法必须在非泛型静态类中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!