首页 > 解决方案 > 在新对象中通过引用修改静态值变量

问题描述

我正在尝试将一堆静态值变量修改为静态类中的字段。它们需要在某种结构中初始化,并附加一个字符串,但外部世界应该能够直接获取变量。

这是我正在尝试做的基本代码转储(忽略 DoStuff() 内部的细节;只是我正在尝试执行的操作的一个示例):

public unsafe static class StaticVariables
{
    public static int foo;
    public static int bar;
    ...
    public static int bazinga;

    static IEnumerable<StaticInteger> intList = new List<StaticInteger>
    {
        new StaticInteger(&foo,"foo"),
        new StaticInteger(&bar,"bar"),
        ...
        new StaticInteger(&bazinga,"bazinga")
    };

    public static void DoStuff()
    {
        foreach(StaticInteger integer in intList)
        {
            if(integer.identifier=="foo") *integer.pValue = 30;
            if (integer.identifier == "bar") *integer.pValue = 23;
        }
        Console.WriteLine("{0} {1}", foo, bar);
    }

}

public unsafe class StaticInteger
{
    public int* pValue;
    public string identifier;

    public StaticInteger(int* pValue, string identifier)
    {
        this.pValue = pValue;
        this.identifier = identifier;
    }
}

我无法获取我想要的 foo/bar 的地址。它们是静态的/全局的,所以它们不应该去任何地方。我可以作弊并fixed在 DoStuff 内部使用来初始化列表,但我希望能够在初始化后多次引用我的列表,我不确定这是否安全,因为我们将不再处于固定块中。有没有办法告诉GC“请不要触摸你把这个静态变量放在哪里”?

如果答案是“不要使用指针,而是使用 XYZ”,我会非常高兴。

标签: c#

解决方案


使用只有 getter 而不是字段的属性,您可以将用户限制为仅读取值,并且值可以存储在 Dictionary 而不是列表中。

public static class StaticVariables
{
    public static int foo { get {return values["foo"];}}
    public static int bar { get {return values["bar"];}}
    public static int bazinga { get {return values["bazinga"];}}

    private static Dictionary<String,int> values = new Dictionary<String,int>();

    static StaticVariables()
    {
        values.Add("foo",0);
        values.Add("bar",0);
        values.Add("bazinga",0);
    }

    public static void DoStuff()
    {
        values["foo"] =30;
        values["bar"] =23;
    }
}

推荐阅读