Subclass constructor exception leaves parent class instance
Sorry for a lot of code to read. 开发者_运维技巧It's the simplest way to show the problem.
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();
}
}
}
Can anyone suggest cleanup logic for case when subclass constructor fails?
You will need to put the cleanup logic in the constructor of B, since you cannot have access to the instance reference after the constructor fails.
Here is an example on how you could do this:
class A
{
static Dictionary<int, A> a = new Dictionary<int, A>();
static int i = 0;
int id;
public A()
{
id = ++i;
a[id] = this;
}
protected void Destroy()
{
a.Remove(id);
i--;
}
public static int Count() { return a.Count; }
}
class B : A
{
public B()
{
try
{
throw new Exception();
}
catch (Exception)
{
Destroy();
throw;
}
}
}
Your base class constructor is being called before the exception is thrown, so the object has already been created and assigned to it's spot in a
. If you want the object to not be created by the constructor, then you might want to consider a static method to instantiate a new A instead of using the default constructor. Then, when the instantiation of the object fails (in B) you'll throw the exception before the object is added to the dictionary.
精彩评论