【发布时间】:2017-07-26 14:50:53
【问题描述】:
我有一个带有以下构造函数的 Winforms 应用程序:
public Form1()
{
InitializeComponent();
//Code that enables/disables buttons etc
}
public Form1(int ID)
{
searchByID = ID;
InitializeComponent();
//Code that enables/disables buttons etc
}
选择哪一个?这取决于程序是否由 CMD 启动并添加了参数。这是检查的主要内容:
static void Main(string[] args)
{
//Args will be the ID passed by a CMD-startprocess (if it's started by cmd of course
if (args.Length == 0)
{
Application.Run(new Form1());
}
else if(args.Length>0)
{
string resultString = Regex.Match(args[0], @"\d+").Value;
incidentID = Int32.Parse(resultString);
try
{
Application.Run(new Form1(incidentID));
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
我的问题是:
如何优化构造函数?它们都包含大约 30 行与相同代码一样好的代码,我想通过这样做来解决这个问题:
public Form1()
{
Form1(0)
}
public Form1(int ID)
{
if (ID>0)
{
//it has an ID
}else
{
doesn't have an ID
}
}
但这给了我错误:
不可调用的成员不能像方法一样使用。
如何优化?
【问题讨论】:
-
这里的关键字是“链接”而不是“重载”
-
尽量在构造函数中包含尽可能少的逻辑。除了分配变量之外,没有其他逻辑是可接受的。
-
谢谢本德。我的构造函数没有逻辑。仅链接事件处理程序、隐藏/显示按钮等。我认为这是正确的
标签: c# constructor constructor-overloading