class 列表对象的方法

Method for class list object

我知道这有点奇怪,我确实知道另一种解决此问题的方法,但我想知道是否有可能有一种方法会影响其自身的列表。我来解释一下。

这就是我的解决方法

public class Example
{
    public void Sanitize()
    {
        // Does logic sanitize itself using API
    }

    public static List<Example> Sanitize(List<Example> examples)
    {
        /// returns a list of sanitized Examples
    }
}

示例如何能够独立运行。

// Base Example sanitized
Example example = new Example(...);
example.Sanitize();

我也想做的事

// Whole list sanitized
List<Example> examples = new List<Example> {...};
examples.Sanitize();

有没有办法做到这一点而不是被要求这样做?

List<Example> startingExamples = new List<Example> { ... }
List<Example> endingExamples = Example.Sanitize(startingExamples);

您可以让静态方法迭代并改变列表元素。

public class Example
{
    public void Sanitize()
    {
        // Does logic sanitize itself using API
    }

    public static void Sanitize(List<Example> examples)
    {
        foreach (var example in examples)
        {
            example.Sanitize();
        }
    }
}

请注意,您不能在迭代列表时修改列表本身,但可以更改列表中的元素。

您可以使用 extension method 向列表添加功能。

static class ExtensionMethods
{
    public static void Sanitize(this List<Example> source)
    {
        foreach (var item in source) item.Sanitize();
    }
}

现在您可以这样做了:

var list = new List<Example>();
list.Sanitize();

看起来你可以使用 extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type.

扩展方法是 static class 上的 static 方法,它对使用它的代码可见。例如,public 代码。该方法的第一个参数是该方法操作的类型,必须在前面加上this修饰符。

所以,例如,你可以做这样的事情...

public static class EnumerableOfExampleExtensions
{
    public static void Sanitize(this IEnumerable<Example> examples) /*or List is fine*/
    {
        // Null checks on examples...
        foreach (var example in examples)
        {
            example.Sanitize();
        }
    }
}

然后你可以在任何 IEnumerable<Example>.

上将其作为实例方法调用
List<Example> examples = new List<Example>();
examples.Sanitize();