【发布时间】:2017-09-10 22:37:15
【问题描述】:
这里是学生。
正在处理当前的 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;
}
}
【问题讨论】:
-
未定义某些内容,CollectionManager 未定义字典或在需要时未由其中一个类组成实例。鉴于您提供的代码,很难说。
-
我是否可以提供代码的任何其他部分来帮助确定未定义的内容?只是不想发布所有内容,并且与损坏的部分相比,代码量难以阅读。
-
我认为问题出在您的集合设置器中。您的私人字典
_collections可能未使用字典的新实例进行初始化。所以在你有private Dictionary<string, List<Card>> _collections的地方。应该是private Dictionary<string, List<Card>> _collections = new Dictionary<string, List<Card>>();请检查一下。当我刚开始在 c# 中使用属性时,我也有同样的痛苦。 -
@DylanColeDuke 通常,CollectionManager 的整个类将有助于确定是否定义了“Collections”。如果这就是你拥有的所有代码,那么 Collections 没有定义。
-
您正在添加
null作为键的值...
标签: c# list dictionary