2009-10-27 20 views
0

我想一些用戶控件,相關信息保存到像這樣的列表:C#:將類類型保存到變量中?

List<UserControlDetails> myList; 
public UserControlDetails 
{ 
    string Description { get; set; } 
    Type UserControlType { get; set; } 
} 

現在,如果我在一個ListView顯示此列表,我希望能夠例如開始我的用戶通過SelectedItem屬性如

//SelectedItem.UserControlType = MyMainViewModel; 
var tmp = new SelectedItem.UserControlType(); //This will return a new instance of MainViewModel 

任何想法如何做到這一點?還是其他想法?

非常感謝!

乾杯

編輯:感謝一堆的答覆。另一個問題:如何將「MaiNViewModel」的類型保存到類型變量中?我得到「類名稱無效」錯誤

編輯2:明白了,它是typeof()。現在我會嘗試的方法和儘快

回答

6

報到我想你想:

object tmp = Activator.CreateInstance(SelectedItem.UserControlType); 

如果總是會出現一些常見類型的後裔(如UserControl),那麼你可以丟:

Type type = SelectedItem.UserControlType; 
UserControl tmp = (UserControl) Activator.CreateInstance(type); 
// You can now use the members of UserControl on tmp. 

這是假設有一個公共的無參數的構造函數,雖然,因爲這就是Activator.CreateInstance電話。

0
var tmp = Activator.CreateInstance(SelectedItem.UserControlType); 
0
// assuming you want to use the default constructor 
object control = Activator.CreateInstance(SelectedItem.UserControlType); 
4

髒和簡單的方法:Activator.CreateInstance。 恕我直言,你應該嘗試一下factory

+0

提及工廠+1。如果僅用於創建實例,則不應公開該類型。 – SoftMemes 2009-10-27 15:12:14

+0

感謝您指出工廠模式! – 2009-10-27 15:36:56

0

您可以使用Activator.CreateInstance(類型t)從類型信息創建新實例。