C#-将本地值添加到静态字典

C#-将本地值添加到静态字典,c#,arrays,dictionary,C#,Arrays,Dictionary,我有这个密码 static Dictionary<string, XElement> DName = new Dictionary<string, string> { }; static void Main(string[] args) { DName.Add("RO","FL"); } static void anotherMethod(){ Console.WriteLine(DName["RO"]); //not working, whil

我有这个密码

static Dictionary<string, XElement> DName = new Dictionary<string, string> { };
static void Main(string[] args)
    {
     DName.Add("RO","FL");
    }
static void anotherMethod(){
Console.WriteLine(DName["RO"]);
//not working, while in Main works.
}       
静态字典DName=新字典{};
静态void Main(字符串[]参数)
{
名称。添加(“RO”、“FL”);
}
静态孔隙无热法(){
Console.WriteLine(DName[“RO”]);
//不工作,但在主要工程中。
}       

那么如何从另一种方法访问它呢

类的所有静态和非静态方法共享Dictionary
DName
。该字典中键的存在与否仅取决于它们的插入时间:如果调用

DName.Add("RO","FL");
在调用
anotherMethod()
之前进行,则
DName[“RO”]
应看到该值;如果在调用
anotherMethod()
之前调用了
Add
,或者在调用
anotherMethod()
之前删除了密钥,则查找
“RO”
将失败

请注意,通过静态成员变量传递数据是一种非常脆弱的方法。显式传递参数要好得多-它可以让您更好地控制要传递的内容:

static void AnotherMethod(IDictionary<string,string>){
    Console.WriteLine(dName["RO"]);
}   
static void AnotherMethod(IDictionary){
Console.WriteLine(dName[“RO”]);
}   

另一个方法位于何处,我的意思是在哪个类中?
System.Collections.Generic.KeyNotFoundException was unhandled Message=字典中不存在给定的键。
错误,@TimSchmelter在类程序中,这两种方法您确定
anotherMethod()执行
Add
?清楚地解释您要执行的操作?在哪里调用?anothermethod?