c# 将自定义方法添加到列表

标签 c# list extension-methods

我想添加一个方法来扩展我的列表行为,但我遇到了麻烦。我想在我正在处理的类中使用“扩展”方法。我该怎么做?

我想做的事:

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");
        ...
    }
}

上面的代码给我错误:

Extension method must be defined in a non-generic static class

最佳答案

扩展方法必须是静态的,以便按您希望的方式使用它们。只需将 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 类中:

When the first parameter of a method includes the this modifier, that method is said to be an extension method. Extension methods can only be declared in non-generic, non-nested static classes. The first parameter of an extension method can have no modifiers other than this, and the parameter type cannot be a pointer type.

关于c# 将自定义方法添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502866/

相关文章:

c# - 在 C# 中安全/惯用地提取子数组

c# - 更改焦点上组合框的边框颜色

python - 如何在具有并列数字的列表中找到最大数字

php - 在 PHP 中访问 HTML 无序列表元素

python - 如何在 Python 中实现列表类的 undo() 方法

c# - 为什么我不能让这些扩展工作?

c# - System.Windows.Forms.Timer 是否在与 UI 不同的线程上运行?

c# - 在扩展方法中保存状态

groovy - 有没有一种干净的方法可以在 Kotlin 中使用 Groovy 的扩展方法?

c# - FileNameSizeDelimiteC 必须是常量