我有一个带有以下构造函数的 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
}
}
但这给了我错误:
不可调用的成员不能像方法一样使用。
我该如何优化呢?