牛骨文教育服务平台(让学习变的简单)
博文笔记

【C#】List<T>.ForEach 方法

创建时间:2018-01-05 投稿人: 浏览次数:395

一边遍历list 可以用for 或者foreach去操作,后来发现list本身就有迭代的方法,ForEach

查看MSDN的介绍:ForEach 本身要传一个Action的委托

官方例子:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<String> names = new List<String>();
        names.Add("Bruce");
        names.Add("Alfred");
        names.Add("Tim");
        names.Add("Richard");

        // Display the contents of the list using the Print method.
        names.ForEach(Print);

        // The following demonstrates the anonymous method feature of C#
        // to display the contents of the list to the console.
        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}


匿名函数使用ForEach:
xfcTarget :参数

public List<GameObject> XFCTargets = new List<GameObject>();
 XFCTargets.ForEach(xfcTarget =>
        {
            if (xfcTarget) xfcTarget.SetActive(active);
        });



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。