我有一个WinForms应用程序会与下面的构造函数:优化构造函数重载在C#
public Form1()
{
InitializeComponent();
//Code that enables/disables buttons etc
}
public Form1(int ID)
{
searchByID = ID;
InitializeComponent();
//Code that enables/disables buttons etc
}
哪一个被choosen?这取决于程序是否由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
}
}
但是这给我的错误:
Non-invocable member cannot be used like a method.
我如何优化呢?
这里的关键字是”链接“而不是”重载“ –
尝试在构造函数中尽可能少的逻辑。除分配变量外,其他任何逻辑都不能接受。 –
谢谢班德。我的构造函数中没有逻辑。只有链接事件处理程序,隐藏/显示按钮等,我会认为这是正确的 –