了解IEnumerable

本文深入探讨了 C# 中 IEnumerable 的使用原理及注意事项,包括为何在 foreach 循环中不能修改元素值,解释 yield 关键词的作用,并提供了一个随机选取 IEnumerable 中元素的方法。

首先我是看了一篇很棒的博客

先说IEnumerable,我们每天用的foreach你真的懂它吗?

这里面比较全面的介绍了迭代器的使用原理,很好的回答了博主自己提出的三个问题。然后下面是我自己的一些小结

 

为什么在foreach中不能修改item的值?

答案是IEnumerator的object Current只有get方法,Collection返回的IEnumerator把当前的属性暴露为只读属性,所以对其的修改会导致运行时错误。

一开始我还在想能不能实现set方法,尝试几次后发现是自己犯蠢了,这应该是故意设计成无法修改值的,真要修改值的话只需要把foreach改为for来遍历就好了。

 

什么是yield关键词?

  1. 是简化遍历操作实现的语法糖
  2. 有yield retrun和yield break
  3. 只能使用在返回类型必须为 IEnumerable、IEnumerable<T>、IEnumerator 或 IEnumerator<T>的方法、运算符、get访问器中

作为一种语法糖,yield只是减少了代码量,最终实现还是通过接口实现。

详情可见:c# yield关键字原理详解

 

 

最后mark一下这个IEnumerable随机取值的方法(来源《深入理解C#》),真的很厉害

    //随机取值
    public static class RandomValue
    {
        public static T RandomEnumerableValue<T>(this IEnumerable<T> source, Random random)
        {
            if (source == null)
                throw new ArgumentNullException("sourcce");
            if (random == null)
                throw new ArgumentNullException("random");

            if (source is ICollection)
            {
                ICollection collection = source as ICollection;
                int count = collection.Count;
                if (count == 0)
                {
                    throw new Exception("IEnumerable没有数据");
                }
                int index = random.Next(count);
                return source.ElementAt(index);
            }

            using (IEnumerator<T> iterator = source.GetEnumerator())
            {
                if (!iterator.MoveNext())
                {
                    throw new Exception("IEnumerable没有数据");
                }
                int count = 1;
                T current = iterator.Current;
                while (iterator.MoveNext())
                {
                    count++;
                    if (random.Next(count) == 0)
                        current = iterator.Current;
                }
                return current;
            }
        }
    }

 

转载于:https://www.cnblogs.com/cn2018/p/8985698.html

C#中的IEnumerable是一个接口,属于System.Collections命名空间。它定义了一个用于遍历集合的枚举器(enumerator),是集合类的基础接口。IEnumerable接口包含一个方法GetEnumerator(),用于返回一个实现IEnumerator接口的枚举器。枚举器提供了对集合中元素的逐个访问,以便实现对集合的迭代。通过实现IEnumerable接口,可以使你的集合类可以通过foreach循环来进行遍历。在使用foreach循环遍历集合时,会自动调用集合的GetEnumerator()方法来获取枚举器,然后使用枚举器逐个访问集合中的元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [IEnumerableC#)](https://blog.youkuaiyun.com/qq_64410237/article/details/131695354)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [C#中IEumerable的简单了解](https://blog.youkuaiyun.com/qq_39806817/article/details/115024666)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值