如何从同一对象的构造函数中调用不同的构造函数

本文关键字:构造函数 调用 对象 | 更新日期: 2023-09-27 18:12:39

我有一个类重载了构造函数。我想重构代码,以便调用一种形式的构造函数将参数转换为另一种构造函数可以接受的格式,然后再调用它。

以下是我目前拥有的三个构造函数的代码:
/// <summary>
/// Original Constructor accepting a single dataset
/// </summary>
/// <param name="theData"> The dataset containing the tables to be displayed</param>    
public DataForm(System.Data.DataSet theData)
{
    InitializeComponent();
    // Ensure a DataSets has been passed for display
    if (theData != null)
    {
        // Create a new list and add the single dataset to it
        List<DataSet> tempDataList = new List<DataSet>();
        tempDataList.Add(theData);
        // Assign the list of datasets to the member variable
        this.m_DSList = tempDataList;
    }
    CreateTabPages();
}
/// <summary>
/// Construct the form with tab pages assigned for each dataset
/// </summary>
/// <param name="DataArray">A collection of datasets, each to be displayed on their own tab page</param>
public DataForm(DataSet[] DataArray)
{
    InitializeComponent();
    // Ensure some DataSets have been passed for display
    if (DataArray != null && DataArray.Length > 0)
    {
        // Assign the list of datasets to teh member variable
        this.m_DSList = new List<DataSet>(DataArray);
    }
    CreateTabPages();
}
/// <summary>
/// Construct the form with tab pages assigned for each dataset
/// </summary>
/// <param name="DataList">A collection of datasets, each displayed on their own tab page</param>
public DataForm( List<System.Data.DataSet> DataList )
{
    InitializeComponent();
    // Assign the list of datasets to teh member variable
    this.m_DSList = DataList;
    CreateTabPages();
}

可以看到,在前两个构造函数中有重复的代码,因此需要进行重构。

我知道我可以有一个方法来完成对象的初始化,并从每个构造函数中调用它,但这似乎不是很优雅。

谁能给我指个正确的方向?谢谢。

如何从同一对象的构造函数中调用不同的构造函数

试试这个

public DataForm(System.Data.DataSet theData): this(new List<System.Data.DataSet>{theData}){}
public DataForm(DataSet[] DataArray): this(DataArray.ToList()){}
public DataForm( List<System.Data.DataSet> DataList )
{
    InitializeComponent();
    // Assign the list of datasets to teh member variable
    this.m_DSList = DataList;
    CreateTabPages();
}
  public DataForm()
        {
             InitializeComponent(); 
        }
        public DataForm(DataSet theData): this()
        {
            this.m_DSList= (theData!=null) ? new List<DataSet>{theData}:null;
        }
        public DataForm(DataSet[] DataArray):this()
        {
             this.m_DSList= (DataArray!=null && DataArray.Length > 0) ? new List<DataSet>(DataArray):null;
        }
        public DataForm(List<DataSet> DataList ):this() 
        {           
            this.m_DSList = DataList; 
        }
        //Take this method out from constructor and for a better design but not mandatory
         public void CreateTabPages()
         {
         }