如何在 C# 中将字典初始化为空字典?
csharpprogrammingserver side programming更新于 2025/5/25 11:37:17
要将字典初始化为空字典,请使用 Clear() 方法。它会清除字典并将其清空。
dict.Clear();
之后,使用 Dictionary count 属性检查列表是否为空 −
if (dict.Count == 0) {
Console.WriteLine("Dictionary is empty!");
}
让我们看看完整的代码 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo {
public class Program {
public static void Main(string[] args) {
var dict = new Dictionary < string, string > ();
dict.Clear();
if (dict.Count == 0) {
Console.WriteLine("Dictionary is empty!");
}
}
}
}
输出
Dictionary is empty!

