简体   繁体   English

泛型 - 在List中的每个对象上调用一个方法<T>

[英]Generics - call a method on every object in a List<T>

Is there a way to call a method on every object in a List - eg 有没有办法在List中的每个对象上调用一个方法 - 例如

Instead of 代替

List<MyClass> items = setup();

foreach (MyClass item in items)
   item.SomeMethod();

You could do something like 你可以做点什么

foreach(items).SomeMethod();

Anything built in, extension methods, or am I just being too damn lazy? 内置任何东西,扩展方法,还是我只是太懒了?

Yes, on List<T> , there is: 是的,在List<T> ,有:

items.ForEach(item => item.SomeMethod())

The oddity is that this is only available on List<T> , not IList<T> or IEnumerable<T> 奇怪的是,这仅适用于List<T> ,而不是IList<T>IEnumerable<T>

To fix this, I like to add the following extension method: 要解决此问题,我想添加以下扩展方法:

public static class IEnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
    {
        foreach(var item in items)
            action(item);
    }
}

Then, you can use it on ANYTHING that implements IEnumerable<T> ... not just List<T> 然后,您可以在实现IEnumerable<T> ANYTHING上使用它...而不仅仅是List<T>

items.ForEach(i => i.SomeMethod());

Lists have a ForEach method. 列表具有ForEach方法。 You could also create an IEnumerable extension method, but it kind of goes against the spirit of Linq . 你也可以创建一个IEnumerable扩展方法, 但它违背了Linq的精神

If you need to change a property on MyClass using MyMethod, use the 'Pipe' method from Jon Skeet's morelinq library 如果您需要使用MyMethod更改MyClass上的属性,请使用Jon Skeet的morelinq库中的“Pipe”方法

items = items.Pipe<MyClass>(i => i.Text = i.UpdateText()).ToList()

The possibilities are endless! 可能性是无止境! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM