2012-12-11 50 views
-1

所有,我有一個應用程序,我想從另一個應用程序或作爲獨立的實用程序lanch。爲了便於啓動從程序appB起來的appA的,我用下面的代碼在Main() /Program.cs現在簡單的構造器鏈接

[STAThread] 
static void Main(string[] args) 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.Run(new SqlEditorForm(args)); 
} 

,在SqlEditorForm我有兩個構造

public SqlEditorForm(string[] args) 
    : this() 
{ 
    InitializeComponent(); 

    // Test if called from appB... 
    if (args != null && args.Count() > 0) 
    { 
     // Do stuff here... 
    } 
} 

和deafult

public SqlEditorForm() 
{ 
    // Always do lots of stuff here... 
} 

這對我來說看起來不錯,但是當作爲獨立運行時(args.Length = 0SqlEditorForm(string[] args)構造函數被調用,並且在它之前st eps進入構造函數執行InitializeComponent();,它會將級的所有全局變量初始化,然後將步直接初始化爲默認構造函數。

問題,構造函數的鏈接似乎是以錯誤的順序發生的。我想知道爲什麼?

謝謝你的時間。

+0

真的有什麼問題嗎? –

+0

構造函數的鏈接似乎以錯誤的順序發生。我想知道爲什麼?謝謝。 – MoonKnight

+0

爲什麼要投票。這是一個合法的問題 - 格式良好。拼寫檢查與愛。甚至沒有評論解釋 - 那只是不禮貌... – MoonKnight

回答

1

移動所有的邏輯來構造函數參數,調用構造函數參數的從一個傳遞默認參數值:

public SqlEditorForm() 
    :this(null) 
{   
} 

public SqlEditorForm(string[] args) 
{ 
    InitializeComponent(); 
    // Always do lots of stuff here... 

    if (args != null && args.Count() > 0) 
    { 
     // Do stuff here... 
    } 
} 
+0

但爲什麼應該首先調用無參數構造函數; ':this()'表示調用默認_after_重寫的構造函數。它應該不會影響我放置'InitializeComponent();'應該!!我設置了Main(string [] args)的方式意味着應該總是調用被重寫的構造函數... – MoonKnight

+0

@Killercam對不起,修正了(由於某種原因,最初我考慮過'base'調用..) - 移動所有邏輯帶參數的構造函數。並從你的無參數構造函數中調用該構造函數,傳遞默認參數值。 –

+0

非常感謝。這對我來說是新聞!很明顯,WinForms中構造函數的鏈接順序有所不同。我說得對嗎?再次,感謝您的時間... – MoonKnight