확장 메서드를 일반적이지 않은 정적 클래스에 정의해야 합니다.
오류가 발생합니다.
확장 메서드를 일반적이지 않은 정적 클래스에 정의해야 합니다.
온라인:
public class LinqHelper
다음은 마크 기벨스 코드를 기반으로 한 도우미 클래스입니다.이 오류가 무엇을 의미하는지 정말 혼란스럽습니다. 금요일에 두고 왔을 때 잘 작동했다고 확신하기 때문입니다.
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
확장 메서드를 만들 때 다음 사항을 고려해야 합니다.
- 확장 메서드를 정의하는 클래스는 다음과 같아야 합니다.
static그리고.non-nested - 모든 확장 메서드는 다음과 같아야 합니다.
static방법 - 확장 메서드의 첫 번째 매개 변수는 다음을 사용해야 합니다.
this키워드
정적 함수를 사용하지 않으려면 인수에서 "this" 키워드를 제거하십시오.
키워드 추가static클래스 선언으로:
// this is a non-generic static class
public static class LinqHelper
{
}
Nathan과 같은 버그를 겪고 있는 사람들을 위한 해결책:
즉시 컴파일러에서 이 확장 메서드 오류에 문제가 있는 것 같습니다...추가static나에게도 도움이 되지 않았습니다.
버그의 원인이 무엇인지 알고 싶습니다.
그러나 해결 방법은 동일한 파일에서도 새 확장명 클래스(내포되지 않음)를 작성하고 다시 빌드하는 것입니다.
이 스레드는 제가 찾은 (제한된) 솔루션을 전달할 가치가 있는 충분한 뷰를 얻고 있다고 생각했습니다.대부분의 사람들은 구글에서 해결책을 찾기 전에 'static'을 추가하려고 했을 것입니다! 그리고 저는 다른 곳에서는 이 해결책을 보지 못했습니다.
변경 시도
public class LinqHelper
로.
public static class LinqHelper
로 변경
public static class LinqHelper
나는 이 컴파일러 오류로 머리를 긁적이고 있었습니다.제 수업은 확장 방식이 아니었고, 몇 달 동안 완벽하게 작동했고 정적이지 않은 상태로 있어야 했습니다.저는 새로운 방법을 수업에 포함시켰습니다.
private static string TrimNL(this string Value)
{...}
나는 샘플에서 메소드를 복사했지만 메소드 서명에서 확장 메소드에 사용되는 "this" 수식어를 알아차리지 못했습니다.그것을 제거함으로써 문제가 해결되었습니다.
종속성 주입을 사용하기 위해 프로젝트를 변환하는 중에 이 문제에 부딪혔습니다.메서드 선언에 "this" 키워드가 포함된 경우 VS에서 경고를 표시합니다.저의 경우 모든 메서드 선언에서 "이것"을 제거할 수 있었습니다."이것"을 사용해야 하는 경우, 이를 정적으로 만들어야 합니다.
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
로 변경된.
public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string property)
정적 메서드와 함께 정적 클래스를 사용하지 않으려면 메서드 선언에 "this" 키워드를 사용하지 않도록 코드화해야 할 수 있습니다.일부 메서드에만 "이것"이 필요한 경우 해당 메서드를 별도의 공용 정적 클래스로 이동할 수 있습니다.
확장 메서드는 정적 클래스 안에 있어야 합니다.따라서 정적 클래스 내에 확장 방법을 추가하십시오.
그래서 예를 들어 이것은 이렇게 되어야 합니다.
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;
}
}
정적 클래스로 변경하고 다시 변경해 보십시오.그것은 잘못된 긍정일 때 시각 스튜디오의 불평을 해결할 수도 있습니다.
유사한 문제가 발생하여 'foo' 폴더를 만들고 foo 내부에 'class'를 만든 후 위와 같은 오류가 발생합니다.한 가지 해결책은 앞에서 언급한 "static"을 "public static class LinqHelper"가 될 클래스에 추가하는 것입니다.
foo 폴더 내에 클래스를 만들면 확장 클래스로 간주되므로 다음 내부 규칙이 적용됩니다.
모든 확장 메서드는 정적 메서드여야 합니다.
해결 방법 정전기를 원하지 않는 경우.제 해결 방법은 네임스페이스 바로 아래에 클래스를 만든 다음 "foo" 폴더로 끌어다 놓는 것이었습니다.
언급URL : https://stackoverflow.com/questions/6096299/extension-methods-must-be-defined-in-a-non-generic-static-class
'programing' 카테고리의 다른 글
| C#에서 "수익률 깨짐;"은 무엇을 합니까? (0) | 2023.05.07 |
|---|---|
| MongoDBC# 드라이버:삽입 시 속성 무시 (0) | 2023.05.07 |
| MongoDB Shell에서 ISO 날짜에 일 추가/감산 (0) | 2023.05.07 |
| 열거형 변수의 기본값은 무엇입니까? (0) | 2023.05.07 |
| 이미 삭제한 대용량 파일 때문에 GitHub에 푸시할 수 없습니다. (0) | 2023.05.07 |