简体   繁体   English

扩展方法必须在非泛型静态类中定义

[英]Extension methods must be defined in a non-generic static class

I'm getting the error:我收到错误:

Extension methods must be defined in a non-generic static class扩展方法必须在非泛型静态类中定义

On the line:在线上:

public class LinqHelper

Here is the helper class, based on Mark Gavells code.这是基于 Mark Gavells 代码的辅助类。 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

to

public static class LinqHelper

Following points need to be considered when creating an extension method:创建扩展方法时需要考虑以下几点:

  1. The class which defines an extension method must be non-generic , static and non-nested定义扩展方法的类必须non-genericstaticnon-nested
  2. Every extension method must be a static method每个扩展方法都必须是static方法
  3. The first parameter of the extension method should use the this keyword.扩展方法的第一个参数应该使用this关键字。

如果您不打算使用静态函数,只需去掉参数中的“this”关键字。

Add keyword static to class declaration:在类声明中添加关键字static

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

A work-around for people who are experiencing a bug like Nathan:对于遇到像 Nathan 这样的错误的人的解决方法:

The on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either.动态编译器似乎对此扩展方法错误有问题......添加static也没有帮助我。

I'd like to know what causes the bug?我想知道是什么导致了这个错误?

But the work-around is to write a new Extension class (not nested) even in same file and re-build.解决方法是在同一个文件中编写一个新的扩展类(非嵌套)并重新构建。

Figured that this thread is getting enough views that it's worth passing on (the limited) solution I found.认为该线程获得了足够多的视图,值得传递我找到的(有限的)解决方案。 Most people probably tried adding 'static' before google-ing for a solution!大多数人可能尝试在 google-ing 之前添加“静态”以寻求解决方案! and I didn't see this work-around fix anywhere else.而且我在其他任何地方都没有看到这种解决方法。

Try changing尝试改变

public class LinqHelper

to

 public static class LinqHelper

将其更改为

public static class LinqHelper

I was scratching my head with this compiler error.这个编译器错误让我摸不着头脑。 My class was not an extension method , was working perfectly since months and needed to stay non-static.我的课程不是扩展方法,几个月以来一直运行良好,需要保持非静态。 I had included a new method inside the class:我在类中包含了一个新方法:

private static string TrimNL(this string Value)
{...}

I had copied the method from a sample and didn't notice the "this" modifier in the method signature, which is used in extension methods.我从示例中复制了该方法,但没有注意到方法签名中的“this”修饰符,该修饰符用于扩展方法中。 Removing it solved the issue.删除它解决了问题。

Extension method should be inside a static class.扩展方法应该在静态类中。 So please add your extension method inside a static class.因此,请在静态类中添加您的扩展方法。

so for example it should be like 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;
        }

    }

Try changing it to static class and back.尝试将其更改为静态类并返回。 That might resolve visual studio complaining when it's a false positive.当它是误报时,这可能会解决 Visual Studio 的抱怨。

I encountered a similar issue, I created a 'foo' folder and created a "class" inside foo, then I get the aforementioned error.我遇到了类似的问题,我创建了一个 'foo' 文件夹并在 foo 中创建了一个“类”,然后我得到了上述错误。 One fix is to add "static" as earlier mentioned to the class which will be "public static class LinqHelper".一种解决方法是将前面提到的“静态”添加到将是“公共静态类 LinqHelper”的类中。

My assumption is that when you create a class inside the foo folder it regards it as an extension class, hence the following inter alia rule apply to it:我的假设是,当您在 foo 文件夹中创建一个类时,它会将其视为扩展类,因此以下规则适用于它:

1) Every extension method must be a static method 1) 每个扩展方法都必须是静态方法

WORKAROUND If you don't want static.变通方法 如果您不想要静态。 My workaround was to create a class directly under the namespace and then drag it to the "foo" folder.我的解决方法是直接在命名空间下创建一个类,然后将其拖到“foo”文件夹中。

I ran into this when converting a project to use dependency injection.我在将项目转换为使用依赖注入时遇到了这个问题。 If a method declaration contains the “this” keyword, VS will give the warning.如果方法声明包含“this”关键字,VS 会给出警告。 In my case, I was able to remove “this” from all of the method declarations.就我而言,我能够从所有方法声明中删除“this”。 If using “this” is required, you will have to make it static.如果需要使用“this”,则必须将其设为静态。

 public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)

changed to变成

     public static IOrderedQueryable<T> OrderBy<T>(IQueryable<T> source, string property)

You might need to code around not using the “this” keyword for the method declaration if you want to avoid using a static class with static methods.如果您想避免使用带有静态方法的静态类,您可能需要在方法声明中不使用“this”关键字进行编码。 If “this” is only required for some methods, those methods can be moved to a separate public static class.如果仅某些方法需要“this”,则可以将这些方法移至单独的公共静态类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM