2017-07-26 122 views
1

我有一个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.

我如何优化呢?

+2

这里的关键字是”链接“而不是”重载“ –

+0

尝试在构造函数中尽可能少的逻辑。除分配变量外,其他任何逻辑都不能接受。 –

+0

谢谢班德。我的构造函数中没有逻辑。只有链接事件处理程序,隐藏/显示按钮等,我会认为这是正确的 –

回答

2

你需要做的是:

public Form1() : this(0) 
{ 
} 

public Form1(int ID) 
{ 
    if (ID>0) 
    { 
     //it has an ID 
    } 
    else 
    { 
     //doesn't have an ID 
    } 
} 

这就是所谓的链接构造在一起 - 所以在: this(0)的意思是“你在此构造上运行的代码之前,调用另外一个,并通过‘0’其参数“

+0

谢谢!但是,我会把第一个构造函数完全清空吗?并不会我的主要功能需要编辑? –

+0

由于这已被标记为重复,您可能可以找到关于该问题的答案=) – Rob

+0

谢谢,链接的问题没有解释我的第一个解决问题的方案有什么问题,但因为问题提问者没有有我的错误... –