【发布时间】:2011-02-14 19:04:22
【问题描述】:
我想做这样的事情:
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.
}
这将允许我从任何地方管理Foos 的全局集合。然而,有人告诉我静态类应该始终是无状态的——你不应该使用它们来存储全局数据。总体而言,全球数据似乎不受欢迎。如果我不应该使用静态类,那么解决这个问题的正确方法是什么?
注意:我确实找到了similar question,但给出的答案并不真正适用于我的情况。
【问题讨论】:
标签: c# static singleton global-variables