c# - 保存派生类的集合实例的基类

标签 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; 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/

相关文章:

java - ClassAny 类之间有什么区别(信用 : Any) and class UserAdmin<T>(credit:T) in Kotlin?

c# - 如何将字典的内容复制到 C# 中的新字典?

c# - .NET 中的日期时间

PHP DataMapper 模式 : My class needs an instance of PDO, 我想将它包装在 Db 类中

javascript - 面向对象的 JavaScript 帮助

java - 返回时泛型如何工作?

c# - 不保存到 HDD 的临时文件

c# - 是否可以生成排除内部方法的 .NET 堆栈跟踪?

c# - 当文件类型和文件名未知时,通过 url 在 c# 中下载文件

oop - Autofac - 生命周期和模块