【问题标题】:C# Scope issue with "global" class“全局”类的 C# 范围问题
【发布时间】: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_LookupDictionaryLookup 不是一回事。
  • 另外,使用TryGetValue 而不是ContainsKey[]。还请包含读取或写入Foo所有代码。
  • 提供一个实际重现问题并且没有明显错别字(例如缺少下划线和多余的冒号)的程序。让你的程序更简单更简单,直到问题消失——它应该告诉你它在哪里——或者你有适合页面的东西,有人可以帮助你。请参阅stackoverflow.com/help/mcve 寻求帮助。

标签: c# dictionary scope


【解决方案1】:

如果您想要应用程序的全局对象,请使用单例。

https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Design-Patterns-Singleton

https://github.com/skimedic/presentations/blob/master/Patterns/Creational/Singleton/MySingletonClass.cs

将你的类命名为 DictionaryLoad

public static class DictionaryLoad{ }

代替

private static volatile MySingletonClass _instance;

改成

private static volatile Dictionary<string,string> _instance;

代替

_instance = new MySingletonClass();

使用

_instance = new Dictionary<string, string>() and load the dictionary.

像这样使用你的函数

public static string Dictionary_Lookup(input)
    {   //DictionaryLoad.Instance will return the dictionary now. 

        if(DictionaryLoad.Instance.ContainsKey(input))
        {
            string return_string = DictionaryLoad.Instance[input];
            return return_string;
        }else
        {
            return "ERROR";
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多