我的 C# 程序中有一堆包含静态成员的类,它是该类所有实例的字典集合 - 如下所示:
class A
{
private static Dictionary<int,A> dict = new Dictionary<int, A>();
public static A GetInstance(int handle) { return dict[handle];}
public A(int handle) {this._handle = handle; dict[handle] = this;}
~A() { dict.Remove(_handle);}
private int _handle;
}
我在许多类中都重复了这个,并且想分解出这个公共(public)代码,但不知道如何做到这一点。将其放入普通基类中是行不通的,因为我想为每个具体类创建一个新集合。我感觉一定有一种方法可以用泛型来做到这一点,但我目前还不太清楚如何做到这一点。
例如,这是不对的:
abstract class Base<T>
{
private static Dictionary<int,T> dict = new Dictionary<int, T>();
public static T GetInstance(int handle) { return dict[handle];}
public A(int handle) {this._handle = handle; dict[handle] = this;}
~Base() { dict.Remove(_handle);}
private int _handle;
}
class A : Base<A>
{
}
由于 A 的构造函数不正确,因此无法编译。我在这里错过了一个技巧吗?
最佳答案
这是我使用 IDisposable
interface 的变体实现:
class Base<T> : IDisposable
where T : Base<T>, new()
{
private static Dictionary<int, T> dict = new Dictionary<int, T>();
private static T Get(int handle)
{
if (!dict.ContainsKey(handle))
dict[handle] = new T(); //or throw an exception
return dict[handle];
}
private static bool Remove(int handle)
{
return dict.Remove(handle);
}
public static T GetInstance(int handle)
{
T t = Base<T>.Get(handle);
t._handle = handle;
return t;
}
protected int _handle;
protected Base() { }
public void Dispose()
{
Base<T>.Remove(this._handle);
}
}
class A : Base<A> { }
然后使用它:
using (A a = Base<A>.GetInstance(1))
{
}
这里没有 public
任何源自 Base<T>
的类的构造函数。而静态工厂GetInstance
应该使用方法来创建实例。请记住,仅当 Dispose
时才会从字典中删除实例。方法被调用,所以你应该使用 using
statement或调用Dispose
手动。
但是我想你仍然应该考虑 SLAks 的评论。
关于c# - 保存派生类的集合实例的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14431089/