通过引用新对象来修改静态值变量

时间:2019-05-09 16:40:24

标签: c#

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

这是我要执行的操作的基本代码转储(无视DoStuff()内部的细节;只是我要执行的操作类型的一个示例):< / p>

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的地址。它们是静态/全局变量,因此它们不应随处可见。我可以作弊并在DoStuff中使用fixed来初始化列表,但是我希望能够在初始化后多次引用我的列表,但我不确定这样做是否安全,因为我们将不再在列表中固定块。有没有办法告诉GC“请不要触摸此静态变量的位置”?

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

1 个答案:

答案 0 :(得分:1)

使用仅具有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;
    }
}