C# 用于保存派生类的集合实例的基类
在我的C#程序中有一堆类,其中包含一个静态成员,它是该类所有实例的字典集合,类似这样:C# 用于保存派生类的集合实例的基类,c#,oop,generics,inheritance,C#,Oop,Generics,Inheritance,在我的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; di
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;
}
A类
{
私有静态字典dict=新字典();
公共静态GetInstance(int句柄){return dict[handle];}
公共A(int handle){this.\u handle=handle;dict[handle]=this;}
~A(){dict.Remove(_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>
{
}
抽象类基类
{
私有静态字典dict=新字典();
公共静态GetInstance(int句柄){return dict[handle];}
公共A(int handle){this.\u handle=handle;dict[handle]=this;}
~Base(){dict.Remove(_handle);}
私人内部处理;
}
A类:基本类
{
}
它无法编译,因为的构造函数不正确。我错过了一个技巧吗?这是我使用实现的变体:
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> { }
类基:IDisposable
其中T:Base,new()
{
私有静态字典dict=新字典();
私有静态T Get(int句柄)
{
如果(!dict.ContainsKey(句柄))
dict[handle]=new T();//或引发异常
返回指令[句柄];
}
专用静态布尔删除(int句柄)
{
返回指令移除(手柄);
}
公共静态GetInstance(int句柄)
{
T=基本。获取(句柄);
t、 _handle=handle;
返回t;
}
受保护的内部句柄;
受保护的基(){}
公共空间处置()
{
底座。拆下(此手柄);
}
}
A类:基本或调用Dispose
手动
不过我想你还是应该考虑SLaks的评论 不要这样做;这是内存泄漏。您的终结器将永远不会运行。(你不应该首先使用终结器)@SLaks这可以通过IDisposable
实现而不是终结器来实现吗?@KonstantinVasilcov:这仍然是个坏主意。这不是关于资源管理的问题;我故意遗漏了与此相关的细节。告诉我不要做某事是没有帮助的(尤其是告诉我不应该使用终结器)。
using (A a = Base<A>.GetInstance(1))
{
}