[C#] 확장 메소드는 제네릭이 아닌 정적 클래스에서 정의해야합니다.

오류가 발생했습니다.

확장 메소드는 제네릭이 아닌 정적 클래스에서 정의해야합니다.

라인에서 :

public class LinqHelper

다음은 Mark 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;
    }
}



답변

변화

public class LinqHelper

public static class LinqHelper

확장 메소드를 작성할 때 다음 사항을 고려해야합니다.

  1. 확장 메서드 여야 정의하는 클래스 non-generic, staticnon-nested
  2. 모든 확장 방법은해야합니다 static방법
  3. 확장 메소드의 첫 번째 매개 변수는 this키워드를 사용해야합니다 .

답변

정적 함수를 사용하지 않으려면 인수에서 “this”키워드를 제거하십시오.


답변

static클래스 선언에 키워드 를 추가하십시오 .

// this is a non-generic static class
public static class LinqHelper
{
}


답변

바꿔보십시오

public class LinqHelper

 public static class LinqHelper


답변

로 변경

public static class LinqHelper


답변

Nathan과 같은 버그가 발생하는 사람들을위한 해결 방법 :

즉석 컴파일러가이 확장 메소드 오류에 문제가있는 것 같습니다. 추가 static해도 도움이되지 않습니다.

버그의 원인을 알고 싶습니다.

그러나 해결 방법 은 동일한 파일에 새 중첩 클래스 (중첩되지 않음)를 작성하고 다시 작성하는 것입니다.

이 스레드가 내가 찾은 (제한된) 솔루션을 전달할 가치가있는 충분한 견해를 얻고 있다고 생각했습니다. 대부분의 사람들은 아마도 해결책을 찾기 위해 google-ing하기 전에 ‘정적’을 추가하려고했습니다! 다른 곳에서는이 해결 방법을 보지 못했습니다.


답변

확장 메소드는 정적 클래스 안에 있어야합니다. 따라서 확장 메소드를 정적 클래스 안에 추가하십시오.

예를 들어 다음과 같아야합니다

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;
        }

    }