• C#进阶08——迭代器、特殊语法


    1.迭代器

    1.迭代器是什么

    迭代器(iterator)有时又称光标(cursor)是程序设计的软件设计模式

    迭代器模式提供一个方法顺序访问一个聚合对象中的各个元素     而又不暴露其内部的标识

    在表现效果上看    是可以在容器对象(例如链表或数组)上遍历访问的接口

    设计人员无需关心容器对象的内存分配的实现细节

    可以用foreach遍历的类,都是实现了迭代器的

    2.标准迭代器的实现方法

    关键接口:IEnumeratory,IEnumerable

    命名空间:using System.Collections;

    可以通过同时继承 IEnumeratory 和 IEnumerable 实现其中的方法

    1. class CustomList:IEnumerable,IEnumerator
    2. {
    3. private int[] list;
    4. //从-1开始的光标 用于表示 数据得到了哪个位置
    5. private int position = -1;
    6. public CustomList()
    7. {
    8. list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    9. }
    10. #region IEnumerable
    11. public IEnumerator GetEnumerator()
    12. {
    13. Reset();
    14. return this;
    15. }
    16. #endregion
    17. public object Current
    18. {
    19. get
    20. {
    21. return list[position];
    22. }
    23. }
    24. public bool MoveNext()
    25. {
    26. //移动光标
    27. ++position;
    28. //是否溢出 溢出就不合法
    29. return position < list.Length;
    30. }
    31. //reset是重置光标位置 一般写在获取
    32. //用于第一次重置光标位置
    33. public void Reset()
    34. {
    35. position = -1;
    36. }
    37. }
    38. class Program
    39. {
    40. static void Main(string[] args)
    41. {
    42. Console.WriteLine("迭代器");
    43. CustomList list = new CustomList();
    44. //foreach本质
    45. //1.先获取in后面这个对象的 IEnumberator
    46. // 会调用对象其中的 GetEnumerator 方法来获取
    47. //2.执行得到这个 IEnumerator 对象中的 MoveNext 方法
    48. //3.只要 MoveNext 方法的返回值是true 就会去得到 Current
    49. // 然后复制给 item
    50. foreach (int item in list)
    51. {
    52. Console.WriteLine(item);
    53. }
    54. foreach (int item in list)
    55. {
    56. Console.WriteLine(item);
    57. }
    58. }
    59. }

     3.用yield return 语法糖实现迭代器

    yield return 是C#提供给我们的语法糖

    所谓语法糖,也称糖衣语法

    主要作用就是将复杂逻辑简单化,可以增加程序的可读性    从而减少程序代码出错的机会

    关键接口:IEnumerable
    命名空间:using System.Collections;
    让想要通过foreach遍历的自定义类实现接口中的方法GetEnumerator即可

    1. class CustomList2 : IEnumerable
    2. {
    3. private int[] list;
    4. public CustomList2()
    5. {
    6. list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    7. }
    8. public IEnumerator GetEnumerator()
    9. {
    10. for (int i = 0; i < list.Length; i++)
    11. {
    12. //yield关键字 配合迭代器使用
    13. //可以理解为 暂时返回 保留当前的状态
    14. //一会儿还会再回来
    15. //C#的语法糖
    16. yield return list[i];
    17. }
    18. }
    19. }
    20. class Program
    21. {
    22. static void Main(string[] args)
    23. {
    24. Console.WriteLine("迭代器");
    25. CustomList2 list2 = new CustomList2();
    26. foreach (int item in list2)
    27. {
    28. Console.WriteLine(item);
    29. }
    30. foreach (int item in list2)
    31. {
    32. Console.WriteLine(item);
    33. }
    34. }
    35. }

     4.用yield return 语法糖为泛型类实现迭代器

    1. class CustomList<T> : IEnumerable
    2. {
    3. private T[] array;
    4. public CustomList(params T[] array)
    5. {
    6. this.array = array;
    7. }
    8. public IEnumerator GetEnumerator()
    9. {
    10. for (int i = 0; i < array.Length; i++)
    11. {
    12. yield return array[i];
    13. }
    14. }
    15. }
    16. class Program
    17. {
    18. static void Main(string[] args)
    19. {
    20. Console.WriteLine("迭代器");
    21. CustomList<string> list3 = new CustomList<string>("123", "321", "333", "555");
    22. foreach (string item in list3)
    23. {
    24. Console.WriteLine(item);
    25. }
    26. }
    27. }

     总结

    迭代器就是可以让我们在外部直接通过 foreach 遍历对象中元素而不需要了解其结构

    主要的两种方式

    1.传统方式 继承两个接口 实现里面的方法

    2.用语法糖 yield return 去返回内容 只需要继承一个接口即可

    2.特殊语法 

    1. class Person
    2. {
    3. private int money;
    4. public bool sex;
    5. public string Name
    6. {
    7. get => "张三";
    8. set => sex = true;
    9. }
    10. public int Age
    11. {
    12. get;
    13. set;
    14. }
    15. public Person(int money)
    16. {
    17. this.money = money;
    18. }
    19. public int Add(int x, int y) => x + y;
    20. public void Speak(string str) => Console.WriteLine(str);
    21. }

    1.var隐式类型

    var 是一种特殊的变量类型

    它可以用来表示任意类型的变量

    注意:

    1.var 不能作为类的成员 只能用于临时变量申明时      也就是 一般写在函数语句块中

    2.var 必须初始化

    1. var i = 5;
    2. var s = "123";
    3. var array = new int[] { 1, 2, 3, 4, };
    4. var list = new List<int>();
    5. //在类型不确定的情况下可以用 var 缺点 看代码时需要看后面代码才能确定var代表的类型

    2.设置对象初始值

    申明对象时    可以通过直接写大括号的形式初始化公共成员变量和属性

    1. Person p = new Person (100){ sex=true,Age=18,Name="张三"};
    2. Person p2 = new Person (200){ Age = 18 };

    3.设置集合初始值

    申明集合对象时    也可以通过大括号 直接初始化内部属性

    1. int[] array2 = new int[] { 1, 2, 3, 4, 5 };
    2. List<int> listInt = new List<int>() { 1, 2, 3, 4, 5 };
    3. List listPerson = new List() {
    4. new Person(100),
    5. new Person(100) { Age=10},new Person(1){ sex=true,Name="张三"}
    6. };
    7. Dictionary<int, string> dic = new Dictionary<int, string>()
    8. {
    9. { 1,"123"},
    10. { 2,"222"}
    11. };

     4.匿名类型

    var 变量可以申明为自定义的匿名类型

    1. var v = new { age = 10, money = 11, name = "小明" };
    2. Console.WriteLine(v.age);
    3. Console.WriteLine(v.money);
    4. Console.WriteLine(v.name);

    5.可空类型

    1. //1.值类型是不能赋值为 空的
    2. //int c = null;
    3. //2.申明时 在值类型后面加?可以赋值为空
    4. int? c = null;
    5. //3.判断是否为空
    6. if (c.HasValue)
    7. {
    8. Console.WriteLine(c);
    9. Console.WriteLine(c.Value);
    10. }
    11. //4.安全获取可空类型值
    12. int? value = null;
    13. // 4-1.如果为空 默认返回值类型的默认值
    14. Console.WriteLine(value.GetValueOrDefault());
    15. // 4-2.也可以指定一个默认值
    16. Console.WriteLine(value.GetValueOrDefault(100));
    17. Console.WriteLine(value);
    18. float? f = null;
    19. double? d = null;
    20. object o = null;
    21. if (o != null)
    22. {
    23. o.ToString();
    24. }
    25. //相当于是一种语法糖 能够帮助我们自动去判断是否为空
    26. //如果是null 就不会执行toString 也不会报错
    27. Console.WriteLine(o?.ToString());
    28. int[] arrayInt = null;
    29. //Console.WriteLine(arrayInt[0]);//会报错
    30. Console.WriteLine(arrayInt?[0]);
    31. Action action = null;
    32. //if (action != null)
    33. //{
    34. // action();
    35. //}
    36. action?.Invoke();

    6.空合并操作符

    空合并操作符 ??

    左边值 ?? 右边值

    如果左边值为null 就返回右边值 否则返回左边值

    只要是可以为null的类型都能用

    1. int? intV = null;
    2. //int intI = intV == null ? 100 : intV.Value;
    3. //简写
    4. int intI = intV ?? 100;
    5. Console.WriteLine(intI);
    6. string str = null;
    7. str = str ?? "haha";
    8. Console.WriteLine(str);

    7.内插字符串

    关键符号:$

    用$来构造字符串,让字符串中可以拼接变量

    1. string name = "张三";
    2. int age = 18;
    3. Console.WriteLine($"好好学习,{name},年龄:{age}");

    8.单句逻辑简略写法 

    当循环或者if语句中只有 一句代码时 大括号可以省略 

    1. if (true)
    2. Console.WriteLine("123123");
    3. for (int j = 0; j < 10; j++)
    4. Console.WriteLine(j);
  • 相关阅读:
    智慧城市中的公共服务创新:让城市生活更便捷
    服务器有几种http强制跳转https设置方法
    FastReport .NET 2023.3.10 Crack
    基于JAVA医院预约挂号系统计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    RPC 框架设计 四、Netty高级应用
    工作流引擎:Workflow Engine 7.0 Crack
    猿创征文 第二季| #「笔耕不辍」--生命不息,写作不止#
    EtherNet/IP转profienrt协议网关连接EtherNet/IP协议的川崎机器人配置方法
    HSTS(HTTP 严格传输安全)
    基于FPGA的分形编码器verilog设计——详细版
  • 原文地址:https://blog.csdn.net/weixin_45274937/article/details/126661562