C# 如何向列表中添加自定义方法

4

我希望能够添加一种方法来扩展我的列表行为,但是我遇到了困难。我想要在我正在使用的类中具有'extension'方法。我该如何做?

我想要做以下事情:

class MyClass
{
    public void DoSomething()
    {
        List<string> myList = new List<string>()
        myList.Add("First Value");
        myList.AddMoreValues(); //or myList += AddMoreValues()  ??
    }        

    private void AddMoreValues(this List<string> theList)
    {
        theList.Add("1");
        theList.Add("2");
        ...
    }
}

上面的代码给我报错:
扩展方法必须定义在非泛型静态类中。

3
扩展方法始终带有 static 关键字,并位于 static 类中,在参数中使用 this,例如 (this List<string> theList) - Rahul
2个回答

7

要按照您想要的方式使用扩展方法,它们必须是静态的。只需在方法中添加 static 关键字:

private static void AddMoreValues(this List<string> theList)

但是最好将它放在一个单独的static类中,并使其public(这样更容易组织您的扩展方法),例如:

public static class ListExtensions
{
    public static void AddMoreValues(this List<string> theList)
    {
        theList.Add("1");
        theList.Add("2");
        ...
    }
}

根据C#规范的10.6.9节,扩展方法必须在一个static类中:

当一个方法的第一个参数包含this修饰符时,该方法被称为扩展方法。扩展方法只能在非泛型、非嵌套的静态类中声明。扩展方法的第一个参数除了this以外不能有其他修饰符,并且参数类型不能是指针类型。


1
这个程序相关的内容翻译为中文:它必须位于“Static”类中。是这样的吗? - Rahul
如果您创建的扩展方法具有与您正在扩展的类型相同的签名方法,则永远不会调用扩展方法。 - Rahul
@Rahul 如果这些方法具有相同的签名,你肯定会得到一个模棱两可的方法调用构建错误。 - Mathew Thompson
你是否了解存储过程?如果是的话,能否帮我看一下我的一个问题? - Rahul
1
@user1208908 噢,好的,派生类应该没问题。 - Mathew Thompson
显示剩余3条评论

1

你应该在一个单独的、静态类中定义扩展方法。

class MyClass
{
    public void DoSomething()
    {
        List<string> myList = new List<string>()
        myList.Add("First Value");
        myList.AddMoreValues();
    }        
}

public static class ExtensionMethods
    public static void AddMoreValues(this List<string> theList)
    {
        theList.Add("1");
        theList.Add("2");
        ...
    }
}

AddMoreValues 不应该是私有的。 - Eric
我不希望所有的列表都能够做到这一点 - 只有 MyClass 中的列表可以。但我明白了。 - Cameron Castillo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接