我想添加一个方法来扩展我的列表行为,但我遇到了麻烦。我想在我正在处理的类中使用“扩展”方法。我该怎么做?
我想做的事:
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/