【发布时间】:2011-12-15 15:49:50
【问题描述】:
我有一个具有重载构造函数的类。我想重构代码,以便对构造函数的一种形式的调用将参数转换为另一个构造函数接受的格式,然后调用它。
这是我目前拥有的三个构造函数的代码:
/// <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();
}
如您所见,前两个构造函数中有重复代码,因此需要重构。
我知道我可以有一个方法来初始化对象并从每个构造函数中调用它,但这似乎不是很优雅。
谁能指出我正确的方向? 谢谢。
【问题讨论】:
-
如果前两个构造函数接收到 null,您是否要让
m_DSList未初始化(或声明的任何内容)? -
CreateTabPages() 方法将处理 m_DSList 为空,但您发现它很好。我会相应地评论我的代码。
标签: c# constructor