2012-03-20 113 views
0

短:调用构造函数基地一个孩子后,构造函数

我如何可以调用构造函数基地子类构造函数后,没有在子类构造函数添加额外的代码?

整个故事:

我有一个基类构造函数通过其子与反射特性的循环。 唯一的问题是它必须在初始化后调用,这发生在子类ctor中。

public class Parent 
{ 
    public Parent() 
    { 
     DoReflectionStuff(); 
    } 

    private void DoReflectionStuff() 
    { 
     // Do reflection stuff on child's properties 
    } 
} 

public class Child : Parent 
{ 
    public string Name { get; private set; } 

    public int Age { get; private set; } 

    public Child(string Name, int Age) : base() 
    { 
     this.Name = Name; 
     this.Age = Age; 
    } 
} 

我不想在调用DoReflectionSuff()的子控件中添加额外的代码。

请帮助:)

谢谢

+0

看起来像c#/ .net,但它总是一个好主意,提到这一点。正如威尔指出的那样 - 你不能。 – Bond 2012-03-20 17:43:01

回答

0

你不能。基地ctor总是先运行。

您可能需要查看factory method pattern以便在获取课程实例之前控制构造和配置。您必须使用factory方法构造类的实例,并且factory方法始终确保实例在返回之前正确配置。

public abstract class Parent 
{ 
    protected Parent(){} 

    private void DoReflectionStuff() 
    { 
     // Do reflection stuff on child's properties 
    } 

    public static T Create<T>() where T : Parent 
    { 
     var temp = Activator.CreateInstance<T>(); 
     temp.DoReflectionStuff(); 
     return temp; 
    } 
}