【发布时间】:2017-08-30 13:23:38
【问题描述】:
我正在尝试将相当于全局字典的内容添加到某些 C# 代码中。我知道全局变量在 C# 中技术上不存在,所以我使用的是没有命名空间的静态类。我的代码是这样的
public static class GlobalClass
{
public static Dictionary<string,string> Foo = new Dictionary<string,string>();
public static void Dictionary_Load()
{
//Load Dictionary from database.
// When I break at the end of this function I see the Dictionary has data in it.
}
public static string Dictionary_Lookup(input)
{
if(Foo.ContainsKey(input))
{
string return_string = Foo[input];
return return_string;
}else
{
return "ERROR";
}
}
}
在另一种形式中,我这样称呼这个类:
namespace MainFormNamespace
{
public partial class : MainForm : Form
{
....
DictionaryLoad();
string test = DictionaryLookup("Bar") //I know "Bar" is in the dictionary
.....
}
}
当我运行它时,我在 Dictionary_Load 返回之前和 Dictionary_Lookup 中的 if 语句处设置了一个断点。当我查看 Dictionary_Load 末尾的字典时,它已满。当我返回 MainForm 时,字典是空的。当我在 Dictionary_Lookup 中的 if 语句处中断时,字典也是空的。我尝试将这两个类放在同一个命名空间中,但没有奏效。我的范围有问题吗?我在这里遗漏了什么明显的东西吗?
【问题讨论】:
-
Dictionary_Lookup和DictionaryLookup不是一回事。 -
另外,使用
TryGetValue而不是ContainsKey和[]。还请包含读取或写入Foo的所有代码。 -
提供一个实际重现问题并且没有明显错别字(例如缺少下划线和多余的冒号)的程序。让你的程序更简单更简单,直到问题消失——它应该告诉你它在哪里——或者你有适合页面的东西,有人可以帮助你。请参阅stackoverflow.com/help/mcve 寻求帮助。
标签: c# dictionary scope