2017-07-26 125 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

謝謝,鏈接的問題沒有解釋我的第一個解決問題的方案有什麼問題,但因爲問題提問者沒有有我的錯誤... –