【问题标题】:Cannot merge dict<string, object> into masterDict without null reference无法在没有空引用的情况下将 dict<string, object> 合并到 masterDict
【发布时间】:2013-10-17 19:53:46
【问题描述】:

它看起来很简单,但我无法将值附加到我的主字典中。我认为这是因为 dict 有一个对象元素而不仅仅是一个简单的类型,而且我在“masterDict.Add”方法上没有正确的语法。我知道我的一些对象值已设置,一些是空字符串,还有一些是 null,但我不认为这是问题的根源 - 该对象确实存在。它在“newMsg.Value”上崩溃。

我的错误:

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.

    Example Code:

    public class msg
    {
        public string msgId { get; set; }
        public string msgType { get; set; }
        public string lastName { get; set; }
        public string firstName { get; set; }
        public string dateOfBirth { get; set; }
        public string sex { get; set; }
        public string pAddress { get; set; }
        public string pPhone { get; set; }
        public IEnumerable<string> prodCode { get; set; }
        public string dateOfServiceText { get; set; }
     } 
    public static Dictionary<String, msg> masterDict { get; set; }

    public static Dictionary<String, msg> tmpDict = new Dictionary<String, msg>()
    {
        { "1111", new msg { msgId = "1111", msgType = "DFT", firstName="Sachin" }},
        { "1112", new msg { msgId = "1112", msgType = "DFT", firstName="Dina" }},
        { "1113", new msg { msgId = "1113", msgType = "DFT", firstName="Andy" }}
    };

    public static void mergeDict()
    {

        //now insert your new values into the master
        foreach (var newMsg in tmpDict)
            if (newMsg.Value != null)
                masterDict.Add(newMsg.Key, newMsg.Value);
    }

    static void Main(string[] args)
    {
        mergeDict();
    }

【问题讨论】:

    标签: c# dictionary add generic-collections idictionary


    【解决方案1】:

    你从未初始化你的masterDict

    public static Dictionary&lt;String, msg&gt; masterDict { get; set; }

    这不会将其设置为任何内容。在您设置之前它将等于 null:

    masterDict = new Dictionary&lt;String, msg&gt;();

    你可能想在你的类构造函数中这样做。

    【讨论】:

    • 你是对的——那行得通。通常我会这样做。在这种情况下,我最初从“masterDict = msgs.ToDictionary(m => m.msgId);”之类的东西开始由于某种原因,它在没有实例化的情况下工作。那时我不必这样做。所以,我忽略了它。
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2011-06-06
    相关资源
    最近更新 更多