涉及 C#的 foreach问题

当时是用foreach实现遍历,但是函数传入参数是Object类型的,由于Objectl类型没有实现相关接口,所以foreach并不能执行。

那么下面我们来看看,想要使用foreach需要具备什么条件。

需要实现IEnumerable接口或声明GetEnumerator方法的类型。

 下面我们来看看foreach原理,

参考原文  http://blog.csdn.net/guobin_lu/article/details/8812092

为什么有些类可以可以用foreach遍历,有些类却不可以了.经反编译过后得出:

 

 

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Collections;  
      
    namespace Myforeach  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {        
                Person p = new Person();  
                p[0] = "宝马";  
                p[1] = "奥迪";  
                p[2] = "阿斯顿马丁";  
                //for (int i = 0; i < p.Count; i++)  
                //{  
                //    Console.WriteLine(p[i]);  
                //}  
      
                //任何类型,只要想使用foreach来循环遍历,就必须在当前类型中  
                //存在: public IEnumerator GetEnumerator()方法,(一般情况我们会通过实现IEnumerable接口,来创建该方法。)  
                foreach (string item in p)  
                {  
                    Console.WriteLine(item);  
                }  
      
                //IEnumerator etor = p.GetEnumerator();  
                //while (etor.MoveNext())  
                //{  
                //    string str = etor.Current.ToString();  
                //    Console.WriteLine(str);  
                //}  
                Console.ReadKey();  
      
      
            }  
        }  
      
        public class Person : IEnumerable  
        {  
            private List<string> listCar = new List<string>();  
      
            public int Count  
            {  
                get  
                {  
                    return this.listCar.Count;  
                }  
      
            }  
      
            public string this[int index]  
            {  
                get  
                {  
                    return listCar[index];  
                }  
      
                set  
                {  
                    if (index >= listCar.Count)  
                    {  
                        listCar.Add(value);  
                    }  
                    else  
                    {  
                        listCar[index] = value;  
                    }  
                }  
            }  
            public string Name  
            {  
                get;  
                set;  
            }  
            public int Age  
            {  
                get;  
                set;  
            }  
            public string Email  
            {  
                get;  
                set;  
            }  
     
            #region IEnumerable 成员  
      
            //这个方法的作用不是用来遍历的,而是用来获取一个对象  
            //这个对象才是用来遍历的。  
            public IEnumerator GetEnumerator()  
            {  
                return new PersonEnumerator(listCar);  
            }  
     
            #endregion  
        }  
      
        //这个类型,的作用就是用来遍历Person中的List集合的。  
        public class PersonEnumerator : IEnumerator  
        {  
            public PersonEnumerator(List<string> _cars)  
            {  
                cars = _cars;  
            }  
      
            //这个字段中存储的就是Person对象中的listCar集合  
            private List<string> cars;  
      
      
            //假设一开始遍历的对象的索引是-1  
            private int index = -1;  
     
            #region IEnumerator 成员  
      
      
            //表示获取当前正在遍历的那个对象  
            public object Current  
            {  
                get  
                {  
                    if (index < 0)  
                    {  
                        return null;  
                    }  
                    return cars[index];  
                }  
            }  
            //让自定义下标index累加  
            public bool MoveNext()  
            {  
                index = index + 1;  
                if (index >= cars.Count)  
                {  
                    return false;  
                }  
                else  
                {  
                    return true;  
                }  
            }  
      
            public void Reset()  
            {  
                index = -1;  
            }  
     
            #endregion  
        }  
    }  

 如果大家想要详细了解 foreach语句。建议大家学习一下迭代器。

参考网址

http://www.cnblogs.com/yangecnu/archive/2012/03/17/2402432.html

转载于:https://www.cnblogs.com/wenjieyatou/p/5639910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
二维装箱问题是一个经典的计算机科学问题,它涉及到如何将一些矩形物体装进一个固定大小的矩形容器中,使得所有物体都能够被容器包含,同时尽可能地节省容器的空间。 在C#中,可以使用贪心算法来解决二维装箱问题。具体来说,可以按照矩形物体的面积从大到小的顺序对它们进行排序,然后依次将每个物体放置在容器中。当一个物体无法放入当前容器时,就创建一个新的容器,并将该物体放入其中。 以下是一个简单的C#程序,用于实现二维装箱问题的贪心算法: ```csharp using System; using System.Collections.Generic; class Rectangle { public int Width { get; set; } public int Height { get; set; } public Rectangle(int width, int height) { Width = width; Height = height; } public int GetArea() { return Width * Height; } } class Container { public int Width { get; set; } public int Height { get; set; } public Container(int width, int height) { Width = width; Height = height; } public bool CanFit(Rectangle rectangle) { return rectangle.Width <= Width && rectangle.Height <= Height; } } class Program { static void Main(string[] args) { List<Rectangle> rectangles = new List<Rectangle>() { new Rectangle(3, 4), new Rectangle(5, 2), new Rectangle(2, 3), new Rectangle(4, 4), new Rectangle(1, 5), new Rectangle(6, 1) }; int containerCount = 1; List<Container> containers = new List<Container>() { new Container(8, 8) }; rectangles.Sort((r1, r2) => r2.GetArea() - r1.GetArea()); foreach (Rectangle rectangle in rectangles) { bool isPlaced = false; foreach (Container container in containers) { if (container.CanFit(rectangle)) { isPlaced = true; container.Width -= rectangle.Width; container.Height -= rectangle.Height; break; } } if (!isPlaced) { containerCount++; containers.Add(new Container(8, 8)); containers[containerCount - 1].Width -= rectangle.Width; containers[containerCount - 1].Height -= rectangle.Height; } } Console.WriteLine($"需要 {containerCount} 个容器"); } } ``` 在上述程序中,我们首先定义了一个`Rectangle`类来表示矩形物体,以及一个`Container`类来表示容器。然后,我们创建了一个包含一些矩形物体的列表,并按照面积从大到小的顺序对它们进行了排序。接下来,我们创建了一个空的容器列表,并将一个初始容器添加到其中。然后,我们遍历每个矩形物体,并尝试将其放入当前容器中。如果当前容器无法容纳该物体,则创建一个新的容器,并将该物体放入其中。最后,我们输出需要的容器数量。 请注意,在上述程序中,我们假设容器的大小为8x8,但你可以根据自己的需求修改容器的大小。同时,该算法并不能保证得到最优解,但通常可以得到较好的近似解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值