无法在没有空引用的情况下将字典<字符串、对象>合并到 masterDict 中

本文关键字:对象 字符串 合并 masterDict 字典 情况下 引用 | 更新日期: 2023-09-27 18:35:46

它接缝很简单,但我无法将值附加到我的主字典中。我认为这是因为字典有一个对象元素而不仅仅是一个简单的类型,而且我在"masterDict.Add"方法上没有正确的语法。我知道我的一些对象值已设置,一些是空字符串,有些是空的,但我认为这不是问题的根源 - 对象确实存在。它在"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();
    }

无法在没有空引用的情况下将字典<字符串、对象>合并到 masterDict 中

您从未初始化过masterDict

public static Dictionary<String, msg> masterDict { get; set; }

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

masterDict = new Dictionary<String, msg>();

您可能希望在类构造函数中执行此操作。