• C# 中 foreach的用法 (补List 的 ForEach细节)


    foreach有点像是for的增强版

    在C#中有时候会遇到需要循环输出的情况,比如这样:

    using Syatem
    using System.Collections;
    using System.Collections.Generic;
    
    class one {
        int[] A = { 1, 2, 3, 4, 5 };
        void Main()
        {
         //for
    for (int i = 0; i < A.Length; i++) Console.WriteLine(A[i]);
         //foreach
    foreach (int i in A) Console.WriteLine(i); } }

    可以看出,当不需要麻烦的操作的时候,不需要针对第 i 元素进行奇怪的操作时,foreach提高了写代码的整洁和效率;


    注:

    1.foreach中的 i 就是A中的元素,如果A是字符串,则应该写为

    foreach (char i in A)
     Console.WriteLine(i);

    2.不要在foreach中试图增删,这样会报异常!需使用for!

    3.List中有一个ForEach,可以实现在循环内增删,关于此还有挺多可以说的:

      List中ForEach是有委托的:要对 Action<T> 的每个元素执行的 List<T> 委托

    标准写法: public void ForEach (Action<T> action); ,然后官方给出了一个示例,由此就可以看出用法了:

     1 using System;
     2 using System.Collections.Generic;
     3 
     4 class Program
     5 {
     6     static void Main()
     7     {
     8         List<String> names = new List<String>();
     9         names.Add("Bruce");
    10         names.Add("Alfred");
    11         names.Add("Tim");
    12         names.Add("Richard");
    13 
    14         // Display the contents of the list using the Print method.
    15         names.ForEach(Print);
    16 
    17         // The following demonstrates the anonymous method feature of C#
    18         // to display the contents of the list to the console.
    19         names.ForEach(delegate(String name)
    20         {
    21             Console.WriteLine(name);
    22         });
    23     }
    24 
    25     private static void Print(string s)
    26     {
    27         Console.WriteLine(s);
    28     }
    29 }
    30 /* This code will produce output similar to the following:
    31  * Bruce
    32  * Alfred
    33  * Tim
    34  * Richard
    35  * Bruce
    36  * Alfred
    37  * Tim
    38  * Richard
    39  */
    点击查看全部示范代码

    by the way,此操作是O(n)操作。

  • 相关阅读:
    c++内存管理5-虚拟内存4区结构图
    C++内存管理5-处理new分配内存失败情况(转)
    C++内存管理4-Windows编程中的堆管理(转)
    C++内存管理3-探讨C++内存和回收
    C++内存管理2-内存泄漏
    VS2015远程调试
    C++内存管理1-64位系统运行32位软件会占用更多的内存吗?
    ffmpeg安装步骤
    golang字符串拼接
    如何严格设置php中session过期时间
  • 原文地址:https://www.cnblogs.com/wayne-tao/p/11313670.html
Copyright © 2020-2023  润新知