它看起来很简单,但我无法将值附加到我的主字典中。我认为这是因为 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();
}