编译器让我让这个函数变为静态

Yog*_*ear 0 c# linq

我不知道为什么,但是visual studio的编译器让我让这个函数变得静态.

我有很多字符串列表

List<string> universe = new List<string>();
List<string> foo1 = new List<string>();
List<string> foo2 = new List<string>();
List<string> foo3 = new List<string>();
.
.
.
List<string> fooN = new List<string>();
Run Code Online (Sandbox Code Playgroud)

一些列表可能是空的而其他列表有数据,我想在有数据的人之间交叉,所以我做了这个函数:

public List<string> IntersectIgnoreEmpty(this List<string> list, List<string> other)
{
    if (other.Any())
        return list.Intersect(other).ToList();
    return list;
}
Run Code Online (Sandbox Code Playgroud)

它给了我错误,直到我把它变成静态.我不知道为什么.

Maa*_*ten 6

您正在定义扩展方法,因为您已将this关键字添加到第一个参数.

扩展方法需要在静态类中定义为静态方法.

扩展方法被定义为静态方法,但是通过使用实例方法语法来调用.它们的第一个参数指定方法操作的类型,参数前面有this修饰符.当您使用using指令将命名空间显式导入源代码时,扩展方法仅在范围内.

如果要定义"普通"方法,请删除this关键字,它将是您类上的实例方法.