首页 > 其他 > 详细

Foreach循环输出索引值

时间:2017-12-27 11:22:41      阅读:267      评论:0      收藏:0      [点我收藏+]

循环输邮索引值,使用for是没有任何问题:

技术分享图片

 

技术分享图片
 class Bh
    {
        public string[] str { get; set; }

        public void TestFor()
        {
            for (int i = 0; i < str.Length; i++)
            {
                Console.WriteLine("index:{0},Value:{1}", i, str[i]);
            }
        }
    }
Source Code

 

运行程序:

技术分享图片

 

但是,某一情况之下,你在程序中,是使用foreach方法进行循环的,但又想输出索引的话,那怎样实现呢?
技术分享图片

 

技术分享图片
class Bh
    {
        public string[] str { get; set; }

        public void TestFor()
        {
            for (int i = 0; i < str.Length; i++)
            {
                Console.WriteLine("index:{0},Value:{1}", i, str[i]);
            }
        }

        public void TestForeach()
        {
            int idx = 0;
            foreach (string s in str)
            {
                Console.WriteLine("index:{0},Value:{1}", idx, s);
                idx++;
            }
        }
    }
Source Code


再次运行,结果可见:
技术分享图片

 

Foreach循环输出索引值

原文:https://www.cnblogs.com/insus/p/8124407.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!