Mat*_*hew 11 c# singleton static global-variables
我想做这样的事情:
public class Foo {
// Probably really a Guid, but I'm using a string here for simplicity's sake.
string Id { get; set; }
int Data { get; set; }
public Foo (int data) {
...
}
...
}
public static class FooManager {
Dictionary<string, Foo> foos = new Dictionary<string, Foo> ();
public static Foo Get (string id) {
return foos [id];
}
public static Foo Add (int data) {
Foo foo = new Foo (data);
foos.Add (foo.Id, foo);
return foo;
}
public static bool Remove (string id) {
return foos.Remove (id);
}
...
// Other members, perhaps events for when Foos are added or removed, etc.
}
Run Code Online (Sandbox Code Playgroud)
这将允许我Foo从任何地方管理s 的全局集合.但是,我被告知静态类应该始终是无状态的 - 您不应该使用它们来存储全局数据.总的来说,全球数据似乎不受欢迎.如果我不应该使用静态类,那么解决这个问题的正确方法是什么?
注意:我确实找到了类似的问题,但给出的答案并不适用于我的情况.
har*_*rpo 10
谁保持静态课程应该是无国籍的?静态意味着.
只知道静态类在CLR中的工作原理:
还要注意并发问题.
作为旁注,令人惊讶的是人们经常说"不要使用X".就像有人走进你的工具并指着六个工具说:"这些工具是不好的做法." 这没有意义.