当前位置: 首页 > wzjs >正文

网站短链接怎么做的it教育培训机构

网站短链接怎么做的,it教育培训机构,自己做盗号网站,ps做网站界面在 C# 中,要使用 foreach 循环遍历一个对象,该对象必须满足以下条件之一: 1. 实现 IEnumerable 或 IEnumerable 接口 非泛型版本:System.Collections.IEnumerable public class MyCollection : IEnumerable {private int[] _da…

在 C# 中,要使用 foreach 循环遍历一个对象,该对象必须满足以下条件之一:

1. 实现 IEnumerable 或 IEnumerable 接口

  • 非泛型版本:System.Collections.IEnumerable
public class MyCollection : IEnumerable
{private int[] _data = { 1, 2, 3 };public IEnumerator GetEnumerator(){return _data.GetEnumerator();}
}
  • 泛型版本:System.Collections.Generic.IEnumerable(推荐)
public class MyCollection<T> : IEnumerable<T>
{private List<T> _data = new List<T>();public IEnumerator<T> GetEnumerator(){return _data.GetEnumerator();}IEnumerator IEnumerable.GetEnumerator() // 显式实现非泛型接口{return GetEnumerator();}
}

2. 提供 GetEnumerator() 方法的公共非泛型实现

  • 如果类没有显式实现 IEnumerable,但提供了返回 IEnumerator 的公共方法,foreach 仍可工作:
public class MyCollection
{private int[] _data = { 1, 2, 3 };public IEnumerator GetEnumerator(){return _data.GetEnumerator();}
}

3. 使用 yield return 自动生成枚举器

  • 编译器会自动为包含 yield return 的方法生成 IEnumerable 实现:
public class MyCollection
{public IEnumerable<int> GetItems(){yield return 1;yield return 2;}
}// 使用时:
foreach (var item in new MyCollection().GetItems()) { ... }

4. 数组或字符串(语言内置支持)

  • 数组和字符串即使未显式实现接口,也能直接用 foreach 遍历(编译器特殊处理):
int[] array = { 1, 2, 3 };
foreach (int num in array) { ... } // 合法string str = "hello";
foreach (char c in str) { ... }    // 合法

关键点总结

  • 必须:对象需提供 GetEnumerator() 方法(通过接口或显式实现)。
  • 推荐:优先使用泛型接口 IEnumerable 以获得类型安全和性能优势。
  • 例外:数组和字符串是语言内置的特殊类型。

示例:完整泛型实现

using System.Collections.Generic;public class MyList<T> : IEnumerable<T>
{private List<T> _items = new List<T>();public void Add(T item) => _items.Add(item);public IEnumerator<T> GetEnumerator() => _items.GetEnumerator();System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()=> GetEnumerator();
}// 使用:
var list = new MyList<int>();
list.Add(1);
list.Add(2);
foreach (var item in list) { ... } // 正常遍历

通过满足上述条件,任何自定义对象都可以使用 foreach 遍历。

在这里插入图片描述

http://www.dtcms.com/wzjs/520438.html

相关文章:

  • 重庆网站编辑职业学校天气预报最新天气预报
  • 企业网站建设电话网站推广优化外包便宜
  • 随申行是国企嘛?优化二十条
  • 网站接入协议及接入商资质深圳百度seo公司
  • wow电影在线观看seo 视频
  • 合肥网站建设设计公司哪家好电商网站建设教程
  • joomla可以做预订类网站吗河北网络推广技术
  • 问答网站建设杭州seo公司哪家好
  • 专科网站建设论文中国十大网站
  • 轻松seo优化排名 快排江苏seo推广
  • 反腐网站建设的目的查域名的网址
  • 如何做下载网站长沙网站建站模板
  • 网站设计与建设课程2022今天刚刚发生地震了
  • 网站做填充友情链接什么意思
  • 做家具的外国网站网络优化需要哪些知识
  • 哪里能找到免费网站百度云登录入口
  • 士兵突击网站怎么做小说百度风云榜
  • 新乡 网站开发百度推广怎么提高关键词排名
  • 百度站长平台快速收录怎么弄推广网站有哪些
  • 网站主体备案信息查询互联网营销师培训多少钱
  • 传媒公司网站模板网站策划是做什么的
  • 舆情报告分析案例百度seo关键词优化费用
  • 用什么软件做网站最好梧州网站seo
  • 重庆品牌网站建设公司排名搜索引擎查重
  • 运营网站开发工作网站快速刷排名工具
  • 网上书店网网站建设企业培训计划
  • 怎么建设独立网站网络营销案例分析ppt
  • 给自己的网站起名字新闻头条国内大事
  • 招商加盟网站大全汇总2023年8月份新冠病毒
  • 长丰县住房和建设局网站seo是什么字