c# - 在新对象中通过引用修改静态值变量
问题描述
我正在尝试将一堆静态值变量修改为静态类中的字段。它们需要在某种结构中初始化,并附加一个字符串,但外部世界应该能够直接获取变量。
这是我正在尝试做的基本代码转储(忽略 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”,我会非常高兴。
解决方案
使用只有 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;
}
}
推荐阅读
- angular - 使用动画时角度平滑滚动不起作用
- java - A* 算法未到达危险节点的终点
- camunda - 获取流的当前正在执行的任务
- amazon-web-services - ec2_ami_copy - 未处理的异常 - 错误(104,'连接被对等方重置')
- c# - 访问 For Loop ASP.Net MVC 5 之外的所有记录
- python - 检查文本文件中的单词
- javascript - Howler 音频搜索总是返回 0
- c# - EF Core“无法为标识列插入显式值”,尽管 IDENTIY_INSERT 设置为 ON
- macos - macOS 上的“打开方式”如何在内部填充?
- powershell - 转义大括号似乎在 SendKeys 中不起作用