添加Lesson8

This commit is contained in:
2025-10-14 16:07:14 +08:00
parent 3c4123d514
commit c86de4e6be
7 changed files with 240 additions and 0 deletions
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+89
View File
@@ -0,0 +1,89 @@
using System.Collections.Generic;
namespace Lesson8_Dictionary
{
internal class Program
{
static void Main(string[] args)
{
#region Dictionary本质
//可以将Dictionary理解为 拥有泛型的Hashtable
//他也是极于剑的哈希代码组织起来的 键/值对
//键值对类型从Hashtable的object变为了可以自己指定的泛型
#endregion
#region
Dictionary<int, string> dictionary = new Dictionary<int, string>();
#endregion
#region
#region
//注意:不能出现相同键
dictionary.Add(1, "111");
dictionary.Add(2, "222");
dictionary.Add(3, "333");
#endregion
#region
//1.只能通过键去删除
// 删除不存在的键 无反应
dictionary.Remove(1);
dictionary.Remove(4);
//2.清空
dictionary.Clear();
#endregion
#region
//1.通过键查看值
//注意:找不到直接报错,而不是像hashtable一样无反应
dictionary.Add(1, "111");
dictionary.Add(2, "222");
dictionary.Add(3, "333");
Console.WriteLine(dictionary[2]);//"222"
//Console.WriteLine(dictionary[4]);//不会像hashtable一样无反应而是直接报错
//2.查看是否存在
// 根据键检测
if (dictionary.ContainsKey(1) )
{
Console.WriteLine("存在键为1的键值对");
}
// 根据值检测
if (dictionary.ContainsValue("111"))
{
Console.WriteLine("存在值为111的键值对");
}
#endregion
#region
Console.WriteLine(dictionary[1]);
dictionary[1] = "999";
Console.WriteLine(dictionary[1]);
#endregion
#endregion
#region
Console.WriteLine("---------------------------");
//长度
Console.WriteLine(dictionary.Count);
//1.遍历所有键
Console.WriteLine("---------------------------");
foreach (int item in dictionary.Keys)
{
Console.WriteLine(item);
Console.WriteLine(dictionary[item]);
}
//2.遍历所有值
Console.WriteLine("---------------------------");
foreach (string item in dictionary.Values)
{
Console.WriteLine(item);
}
//3.键值对一起遍历
Console.WriteLine("---------------------------");
foreach (KeyValuePair<int, string> pair in dictionary)
{
Console.WriteLine($"键:{pair.Key} 值:{pair.Value}");
}
#endregion
}
}
}