c# 将自定义方法添加到列表
c# Add custom method to Lists
我想添加一个方法来扩展我的列表行为,但我遇到了问题。我想在我正在处理的 class 中使用 '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");
...
}
}
上面的代码给我错误:
Extension method must be defined in a non-generic static class
您应该在单独的 static class.
中定义扩展方法
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");
...
}
}
扩展方法必须是静态的才能按您希望的方式使用它们。只需将 static
关键字添加到您的方法中:
private static void AddMoreValues(this List<string> theList)
但是你最好将它放在一个单独的 static
class 中并使其成为 public
(这样组织你的扩展方法更容易),比如:
public static class ListExtensions
{
public static void AddMoreValues(this List<string> theList)
{
theList.Add("1");
theList.Add("2");
...
}
}
根据 C# 规范的第 10.6.9 节,扩展方法需要在 static
class 中:
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.
我想添加一个方法来扩展我的列表行为,但我遇到了问题。我想在我正在处理的 class 中使用 '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");
...
}
}
上面的代码给我错误:
Extension method must be defined in a non-generic static class
您应该在单独的 static class.
中定义扩展方法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");
...
}
}
扩展方法必须是静态的才能按您希望的方式使用它们。只需将 static
关键字添加到您的方法中:
private static void AddMoreValues(this List<string> theList)
但是你最好将它放在一个单独的 static
class 中并使其成为 public
(这样组织你的扩展方法更容易),比如:
public static class ListExtensions
{
public static void AddMoreValues(this List<string> theList)
{
theList.Add("1");
theList.Add("2");
...
}
}
根据 C# 规范的第 10.6.9 节,扩展方法需要在 static
class 中:
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.