Skip to main content
 首页 » 编程设计

c#之.NET 中的链接构造函数

2024年02月05日10telwanggs

我尝试通过尽可能重用构造函数来节省代码并降低可维护性的故障率。现在,我遇到了一种情况,我认为我必须复制代码,但也许您知道解决方案。

public class Bar { 
  public List<string> BarList { 
    get; 
    private set; 
  } 
 
  public Bar() { 
    this.BarList = new List<string>(); 
  } 
 
  public Bar(XmlNode node) 
    : this() { 
    //create from xml 
  } 
} 
 
public class Foo: Bar { 
  public List<int> FooList { 
    get; 
    private set; 
  } 
  public Foo() 
    : base() { 
    this.FooList = new List<int>(); 
  } 
 
  public Foo(XmlNode node) 
    : base(node) { 
    //create from enhanced xml 
  } 
} 

每个以 XMLNode 为参数的构造函数调用之前的无参数构造函数进行初始化。但是如何管理,派生类 Foo 调用它自己的无参数构造函数和带有基类的 XmlNode 参数的构造函数?

构造函数链的期望行为是:

Foo(XmlNode)->Bar(XmlNode)->Foo()->Bar() 

请您参考如下方法:

为什么不抽象构造函数的工作? 类似于:[检查新函数初始化]

public class Foo : Bar 
{ 
    public List<int> FooList 
    { 
        get; 
        private set; 
    } 
    public Foo() 
      : base() 
    { 
        Init(); 
    } 
 
    private void Init() { this.FooList = new List<int>(); } 
 
    public Foo(XmlNode node) 
      : base(node) 
    { 
        Init(); 
        //create from enhanced xml 
    } 
}