首页主机资讯c#中for循环如何遍历数组

c#中for循环如何遍历数组

时间2024-09-20 20:58:04发布访客分类主机资讯浏览555
导读:在C#中,你可以使用for循环或者foreach循环来遍历数组。下面是两种方法的示例: 使用for循环遍历数组: int[] array = new int[] { 1, 2, 3, 4, 5 }; for (int i = 0; i...

在C#中,你可以使用for循环或者foreach循环来遍历数组。下面是两种方法的示例:

  1. 使用for循环遍历数组:
int[] array = new int[] {
 1, 2, 3, 4, 5 }
    ;
    

for (int i = 0;
     i <
     array.Length;
 i++)
{
    
    Console.WriteLine("Element at index " + i + ": " + array[i]);

}

  1. 使用foreach循环遍历数组:
int[] array = new int[] {
 1, 2, 3, 4, 5 }
    ;


foreach (int element in array)
{
    
    Console.WriteLine("Element: " + element);

}
    

在这两个示例中,我们都遍历了一个整数数组,并打印出了每个元素。for循环使用索引来访问数组的元素,而foreach循环则直接访问数组的元素。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c#中for循环如何遍历数组
本文地址: https://pptw.com/jishu/700135.html
vertx mybatis的插件机制有哪些 vertx mybatis的SQL映射文件怎么写

游客 回复需填写必要信息