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

时间:2011-10-26 11:23:13

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

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

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

有人能指出我正确的方向吗? 感谢。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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