声明 HashMap
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 47 课,共 66 课。
在 C# 中,HashMap 对应的类型称为 Dictionary。它可以让你存储键值对,以便高效查找。
首先,我们来创建一个空字典:
Dictionary<string, int> fruitInventory = new Dictionary<string, int>();这会创建一个字典,其中键是字符串(水果名称),值是整数(数量)。
现在,我们来向字典中添加一些项目:
fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);运行上述代码后,我们的 fruitInventory 中包含:
- "Apple" → 10
- "Banana" → 15
你也可以用值初始化字典:
Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
{ "Apple", 10 },
{ "Banana", 15 }
};挑战
中等创建一个名为 CreateFruitInventory 的方法,该方法:
- 创建一个新的 Dictionary,键为 string 类型,值为 int 类型
- 添加以下水果和数量:
- "Apple",数量为 5
- "Banana",数量为 10
- "Orange",数量为 7
- 返回创建的 Dictionary
亲手试试
using System;
using System.Collections.Generic;
class Program
{
public static Dictionary<string, int> CreateFruitInventory()
{
// 在这里编写你的代码
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = CreateFruitInventory();
// 显示库存
foreach (var item in inventory)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器