2009-10-27 3 views
0

일부 UserControl-Infos를 다음과 같이 목록에 저장하려고합니다.C# : 변수를 클래스에 저장 하시겠습니까?

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

이제이 ListView를 ListView에 표시하면 UserControl을 시작할 수 있습니다. SelectedItem 속성을 통해

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

같은 모든 아이디어가 어떻게됩니까? 아니면 다른 아이디어?

고마워요!

환호

편집 : 감사 응답을위한 무리. 또 다른 질문 : "MaiNViewModel"의 유형을 유형 변수에 저장하는 방법은 무엇입니까? "클래스 이름이 유효하지 않습니다."오류가 발생합니다.

EDIT2 : 알았어, typeof()입니다. 나는 이제 방법을 시험해보고 가능한 한 빨리보고 할 것이다.

답변

6

로 다시보고 있습니다 캐스팅 :

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. IMHO, factory으로 시도해야합니다.

+0

+1 공장 언급. 인스턴스를 생성하는 데만 사용되는 경우 유형이 노출되어서는 안됩니다. – SoftMemes

+0

공장 패턴을 지적 해 주셔서 감사합니다! –

0

Activator.CreateInstance (유형 t)를 사용하여 유형 정보에서 새 인스턴스를 만들 수 있습니다.

관련 문제