泛型

mac2026-03-17  3

泛 型 泛型

1.泛型 List

C#里支持泛型语法,例如

List<int> aaa = new List<int>();

介绍List, Dictionary等API的使用

官方文档API参考 https://docs.microsoft.com/zh-cn/dotnet/


List,列表类,相当于Java里的ArrayList

List<int> aaa = new List<int>(); Add() Insert() Remove() Count()

支持索引器访问,例如 aaa[i]=12


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp基础语法 { class Program { static void Main(string[] args) { List<int> a = new List<int>(); a.Add(100); a.Add(100); a.Add(100); a.Add(100); a.Add(100); // 普通便利 for (int i = 0; i < a.Count(); i++) { Console.WriteLine(a[i] + " "); } // foreach遍历 foreach(int item in a) { Console.WriteLine(item + " "); } } } }

2.泛型 Dictionary

Dictionary,字典类,相当于Java里的HashMap

new Dictionary<TKey, TValue>()

创建字典,指定Key类型和Value类型

Add(key, value)

增加一对键值,如果key已存在则抛异常

Remove(key)

从字典中删除 key

ContainsKey (key)

判断key是否存在,返回true/false

dict[key]

以key为索引,设置或取值。取值时如果key不存在,则抛出异常。

TryGetValue (key,out value)

尝试获取值,如果存在,则修改value值


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp基础语法 { class Program { static void Main(string[] args) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("name", "major_s"); dict.Add("age", "18"); dict.Add("sex", "男"); dict.Add("phone", "1234567890"); dict.Add("address", "jiangsu"); // 索引添加(推荐) dict["address"] = "jiangyin"; // 先判断,再取值 if (dict.ContainsKey("address")) { String address = dict["address"]; Console.WriteLine(address); } // 尝试取值 dict.TryGetValue("name", out string Value); } } }

3.迭代与枚举遍历

在C#里,集合类有统一的遍历方式 1 foreach方式 2 枚举器方式

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharp基础语法 { class Program { static void Main(string[] args) { List<string> a = new List<string>(); a.Add("major_s"); a.Add("18"); a.Add("男"); a.Add("1234567890"); a.Add("jiangsu"); // 迭代遍历 foreach (string item in a) { Console.WriteLine(item + " "); } // 枚举遍历 List<string>.Enumerator en = a.GetEnumerator(); while (en.MoveNext()) { string item = en.Current; Console.WriteLine(item + " "); } } } }

1官方推荐使用foreach方式遍历 2不支持一边遍历一边删除操作

foreach和枚举器,都是只读遍历

最新回复(0)