2

我的 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 的构造函数不正确,因此无法编译。我在这里错过了一个技巧吗?

4

1 回答 1

2

这是我使用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 的评论。

于 2013-01-21T01:36:51.337 回答