【问题标题】:User input creating Dictionary Key (C#)用户输入创建字典键(C#)
【发布时间】: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&lt;string, List&lt;Card&gt;&gt; _collections的地方。应该是private Dictionary&lt;string, List&lt;Card&gt;&gt; _collections = new Dictionary&lt;string, List&lt;Card&gt;&gt;(); 请检查一下。当我刚开始在 c# 中使用属性时,我也有同样的痛苦。
  • @DylanColeDuke 通常,CollectionManager 的整个类将有助于确定是否定义了“Collections”。如果这就是你拥有的所有代码,那么 Collections 没有定义。
  • 您正在添加 null 作为键的值...

标签: c# list dictionary


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    将您的属性更改为:

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

    【讨论】:

    • 假设使用的是最新版本的 C#。
    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多