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 のコンストラクターが正しくないため、コンパイルに失敗します。ここでトリックがありませんか?