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

Tea*_*ild 3 c# constructor

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

这是我目前拥有的三个构造函数的代码:

/// <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();
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,前两个构造函数中存在重复的代码,因此重新分解.

我知道我可以有一个方法来执行对象的初始化并从每个构造函数中调用它,但这看起来并不优雅.

谁能指出我正确的方向?谢谢.

Ste*_*cya 6

试试这个

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();
}
Run Code Online (Sandbox Code Playgroud)