2013-02-01 45 views
1

我正在創建MDI form,我有一個加載不同表單的方法。現在我需要做一些修改 - 我需要添加從另一個子窗體中調用一個子窗體的功能。C# - 使用泛型類型的方法的實現

因爲我需要這個在幾個不同的地方,我從所有需要這個功能的類繼承了一個新類。我想使它與泛型類型一起工作,這樣我就可以傳遞我可能需要的所有表單類,如LoadAForm(MyForm1)LoadAForm(MyForm2)等等。我希望我清楚自己想要什麼作爲最終結果。

我嘗試這樣做:

protected void LoadAForm<T>(ref T sender) 
{ 
    MainForm frm = this.MdiParent as MainForm; 
    T temp; 
    if (frm != null) 
    { 
     sender = SingletonFormProvider.GetInstance<temp>(frm, true); 
     sender.MdiParent = frm; 
     sender.Dock = DockStyle.Fill; 
     sender.Show(); 
    } 
} 

不工作。但是,當我們在方法中使用泛型時,我幾乎沒有使用泛型的經驗,所以我不知道如何繼續。

我得到一個錯誤使用這種語法是The type or namespace "temp" could not be found...". I'm not even sure that this is the way to do it. GetInstance <>`必須採取與我打電話的形式類型相同的參數。

回答

5

您需要使用類型參數,而不是變量名:

sender = SingletonFormProvider.GetInstance<T>(frm, true); 

此外,爲了確保T是有效的(如您的comment建議),您將需要限制它:

protected void LoadAForm<T>(ref T sender) where T : Form 
+0

我試過,但得到這個錯誤'的類型T不能在泛型類型的方法被用作類型參數「T」 .. 。沒有從「T」到「System.Windows.Forms.Form」的裝箱轉換或類型參數轉換。 – Leron

+0

@Lonon - 你需要在方法上添加一個類型約束,所以'T'只能從'Form'派生。 – Oded

+0

謝謝,問題解決了! – Leron

1

我不認爲你在這裏需要泛型。我想你可以更輕鬆簡單地使用Form作爲具體類型的工作:

protected void LoadAForm(ref Form sender) 
{ 
    MainForm frm = this.MdiParent as MainForm; 
    Form temp; 
    if (frm != null) 
    { 
     sender = SingletonFormProvider.GetInstance(frm, true); 
     sender.MdiParent = frm; 
     sender.Dock = DockStyle.Fill; 
     sender.Show(); 
    } 
} 
相關問題