如何在C#中将键值对添加到静态字典 [英] How to add key value pair to static dictionary in C#
问题描述
我有一个静态字典
public static Dictionary< Guid,Dictionary< string,object>>商店{get;设置;}
我想从另一个类为上面的字典添加值
Guid clientId = Guid.NewGuid();
Dictionary< string,object> storageKeyDictionary = new Dictionary< string,object>(){{parameter,test}};
Storage.Store.Add(clientId,storageKeyDictionary);
但它返回错误为对象引用未设置为对象的实例。在执行时,请告诉我代码有什么问题?
我尝试过:
我试图将值添加到私有静态字典但返回错误。
I have a static dictionary
public static Dictionary<Guid, Dictionary<string, object>> Store {get; set;}
I want to add value to the above dictionary from another class as
Guid clientId = Guid.NewGuid();
Dictionary<string,object> storageKeyDictionary = new Dictionary<string, object>() { { "parameter", "test" }};
Storage.Store.Add(clientId, storageKeyDictionary);
But it return error as "Object reference not set to an instance of an object." while executing, please tell me what is wrong with the code?
What I have tried:
I have tried to add value to private static dictionary but returned error.
推荐答案
您的代码几乎是正确的,但在Storage.Store之前。你缺少Add():
Your code is almost correct, but before Storage.Store.Add() you are missing:
Store = new Dictionary<Guid, Dictionary<string, object>>();
您必须先初始化您的商店对象。使用如下
you have to initialize your store object first.Use like below
public class Program
{
public static Dictionary<Guid, Dictionary<string, object>> Store {get; set;}
static Program()
{
Store=new Dictionary<Guid, Dictionary<string, object>>();
}
public static void Main(string[] args)
{
Guid clientId = Guid.NewGuid();
Dictionary<string,object> storageKeyDictionary = new Dictionary<string, object>() { { "parameter", "test" }};
Store.Add(clientId, storageKeyDictionary);
//Your code goes here
Console.WriteLine("Hello, world!");
}
}
或者你可以直接写成
or you can directly write like
public class Program
{
public static Dictionary<Guid, Dictionary<string, object>> Store =new Dictionary<Guid, Dictionary<string, object>>();
public static void Main(string[] args)
{
Guid clientId = Guid.NewGuid();
Dictionary<string,object> storageKeyDictionary = new Dictionary<string, object>() { { "parameter", "test" }};
Store.Add(clientId, storageKeyDictionary);
//Your code goes here
Console.WriteLine("Hello, world!");
}
}
这篇关于如何在C#中将键值对添加到静态字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!