用户输入创建字典键(C#)

时间:2017-09-10 22:37:15

标签: c# list dictionary

学生在这里。

处理当前的C#项目。

我必须制作List<Card>张扑克牌和Dictionary<string, List<Card>>

列表是独立创建的,字典包含卡片集合。可以在集合中添加或删除卡片。

我在根据用户输入创建字典键时遇到问题

错误是程序运行时,我输入要创建的键的名称。

  

对象引用未设置为对象的实例。

以下是代码块:

Console.Write("What is the name of this collection? ");
string collectionName = Console.ReadLine();
bool found = currentManager.Collections.ContainsKey(collectionName);
if (!found)
 {
    currentManager.Collections.Add(collectionName, null);
 }
else
    Console.WriteLine("That collection name has already been used.");

我使用的是CollectionManager类,我的词典名为_collections。这在这里被称为:

public Dictionary<string, List<Card>> Collections
    {
        get
        {
            return _collections;
        }
        set
        {
            _collections = value;
        }
    }

2 个答案:

答案 0 :(得分:0)

_collections引用是否已初始化为Dictionary实例?根据错误消息,看起来_collections没有指向实例。

答案 1 :(得分:0)

将您的财产更改为:

public Dictionary<string, List<Card>> Collections {get;set;} = new Dictionary<string, List<Card>>();