大量のコードを読み込むことは残念です。それは問題を示す最も簡単な方法です。サブクラスのコンストラクタ例外は親クラスのインスタンスを残します
using System;
using System.Collections.Generic;
namespace P1
{
class A
{
static Dictionary<int, A> a = new Dictionary<int, A>();
static int i = 0;
int id;
public A()
{
id = ++i;
a[id] = this;
}
public static int Count() { return a.Count; }
}
class B : A
{
public B()
{
throw new Exception();
}
}
class Program
{
static void Main(string[] args)
{
try
{
var b = new B();
}
catch
{
// What should be here ????
}
Console.WriteLine(A.Count()); //prints 1 - not good
Console.ReadKey();
}
}
}
誰でもサブクラスのコンストラクタが失敗した場合のクリーンアップロジックを提案できますか?
'B'のコンストラクタが失敗した場合、あなたのプログラムは何とか回復できますか?なぜ「1」は「良くないのですか」? –
bが失敗しても、aのインスタンスは残っており、削除方法はわかりません。 – Marko
@Marko:オブジェクト作成の懸念と辞書へのオブジェクトの挿入の懸念を区別すると、この質問は発生しません。 –