字典默认值作为参数

  • 本文关键字:参数 默认值 字典 c#
  • 更新时间 :
  • 英文 :


我用n个键和零值初始化字典。通过参数,我可以设置一些值。

调用构造函数时,我执行此

public Store(Dictionary<int, int> initialItems = null)
{
items = new Dictionary<int, int>();
for (int i = 0; i < 45; i++) // 45 items should exist
{
int initialAmount = 0; // 0 as starting value
if (initialItems != null) // parameter is passed in?
{
initialItems.TryGetValue(i, out initialAmount); // start with a higher value than 0
}
items.Add(i, initialAmount); // initialize value with 0 or more
}
}
private Dictionary<int, int> items;

我问这是否是通过参数传递起始值的好方法。我只想创建一堆项目并将值设置为 0 或更高的值(如果在其他地方指定(,例如作为构造函数参数。

你也可以像这样将初始字典传递给字典的构造函数:

public Store(Dictionary<int, int> initialItems = null)
{
if (initialItems!=null)
items = new Dictionary<int, int>(initialItems);
else
items = new Dictionary<int, int>();
for (int i = 0; i < 45; i++) // 45 items should exist
{                
if (!items.ContainsKey(i))
items.Add(i, 0); // initialize value with 0
}
}
private Dictionary<int, int> items;

最新更新