代码之家  ›  专栏  ›  技术社区  ›  Marko

子类构造函数异常离开父类实例

  •  0
  • Marko  · 技术社区  · 15 年前

    很抱歉有很多代码要读。这是显示问题的最简单的方法。

    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();
            }
        }
    }
    

    当子类构造函数失败时,有人能建议清理逻辑吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   driis    15 年前

    您需要将清理逻辑放在B的构造函数中,因为在构造函数失败后您无法访问实例引用。

    下面是一个关于如何做到这一点的示例:

    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;
            }
        }
    }
    
        2
  •  0
  •   Kendrick    15 年前

    在引发异常之前,正在调用基类构造函数,因此对象已经创建并分配到 a . 如果希望对象不是由构造函数创建的,则可能需要考虑使用静态方法来实例化新的a,而不是使用默认构造函数。然后,当对象的实例化失败时(在B中),您将在对象添加到字典之前抛出异常。