Los métodos de extensión deben definirse en una clase estática no genérica


Estoy recibiendo el error:

Los métodos de extensión deben definirse en una clase estática no genérica

En la línea:

public class LinqHelper

Aquí está la clase helper, basada en el código de Mark Gavells. Estoy muy confundido en cuanto a lo que significa este error, ya que estoy seguro de que estaba funcionando bien cuando lo dejé el viernes!

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;
    }
}
Author: abatishchev, 2011-05-23

8 answers

Cambiar

public class LinqHelper

A

public static class LinqHelper

Los siguientes puntos deben considerarse al crear un método de extensión:

  1. La clase que define un método de extensión debe ser non-generic, static y non-nested
  2. Cada método de extensión debe ser un método static
  3. El primer parámetro del método extension debe usar la palabra clave this.
 250
Author: crypted,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-14 08:33:13

Añadir palabra clave static a la declaración de clase:

// this is a non-generic static class
public static class LinqHelper
{
}
 21
Author: abatishchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-23 11:02:16

Cámbialo a

public static class LinqHelper
 16
Author: Rik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-23 11:02:25

Intenta cambiar

public class LinqHelper

A

 public static class LinqHelper
 15
Author: Nathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-01 02:27:58

Una solución para las personas que están experimentando un error como Nathan:

El compilador sobre la marcha parece tener un problema con este error de método de extensión... agregar static tampoco me ayudó.

Me gustaría saber qué causa el error?

Pero la solución es escribir una nueva clase de extensión (no anidada) incluso en el mismo archivo y volver a construir.

Pensé que este hilo está recibiendo suficientes vistas que vale la pena pasar (la limitada) solución que encontré. Mas la gente probablemente intentó agregar 'estática' antes de google-ing para una solución! y no vi esta solución de trabajo en ningún otro lugar.

 7
Author: Stephan Luis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-21 10:57:21

El método de extensión debe estar dentro de una clase estática. Así que por favor agregue su método de extensión dentro de una clase estática.

Así que, por ejemplo, debería ser así

public static class myclass
    {
        public static Byte[] ToByteArray(this Stream stream)
        {
            Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
            Byte[] buffer = new Byte[length];
            stream.Read(buffer, 0, length);
            return buffer;
        }

    }
 0
Author: Debendra Dash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 08:06:50

Intente cambiarlo a clase estática y viceversa. Eso podría resolver las quejas de visual Studio cuando se trata de un falso positivo.

 0
Author: visc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-02 18:51:59

Si no tiene la intención de tener funciones estáticas, simplemente elimine la palabra clave "this" en los argumentos.

 0
Author: Rohan Bhosale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-07 06:28:33