基类来保存派生类的集合实例
本文关键字:集合 实例 派生 保存 基类 | 更新日期: 2023-09-27 17:54:53
我的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;
}
我已经在许多类中重复了这个,并且想要分解出这个公共代码,但不知道如何做到这一点。把它放在一个普通的基类中是行不通的,因为我想为每个具体类都创建一个新的集合。我感觉一定有一种方法可以用泛型做到这一点,但我现在还不知道怎么做。
例如:
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
接口实现的变体:
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
语句或手动调用Dispose
。
但是我想你还是应该考虑一下SLaks的评论。