优化C#中的构造函数重载
Optimize constructor overloading in C#
我有一个带有以下构造函数的 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
}
}
但这给了我错误:
Non-invocable member cannot be used like a method.
我该如何优化它?
您需要做的是:
public Form1() : this(0)
{
}
public Form1(int ID)
{
if (ID>0)
{
//it has an ID
}
else
{
//doesn't have an ID
}
}
这称为将构造函数链接在一起 - 因此 : this(0)
表示 "before you run the code in this constructor, call the other one and pass "0" 作为其参数"
我有一个带有以下构造函数的 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
}
}
但这给了我错误:
Non-invocable member cannot be used like a method.
我该如何优化它?
您需要做的是:
public Form1() : this(0)
{
}
public Form1(int ID)
{
if (ID>0)
{
//it has an ID
}
else
{
//doesn't have an ID
}
}
这称为将构造函数链接在一起 - 因此 : this(0)
表示 "before you run the code in this constructor, call the other one and pass "0" 作为其参数"