2008-09-24 4 views
3

generic의 클래스 이름 만 "MyCustomGenericCollection (of MyCustomObjectClass)"형식의 문자열로 가정하고 그 어셈블리의 출처를 모르는 경우 해당 개체의 인스턴스를 만드는 가장 쉬운 방법은 무엇입니까?generic에서 이름을 인스턴스화하는 가장 좋은 방법은 무엇입니까?

도움이된다면 클래스가 IMyCustomInterface를 구현하고 현재 AppDomain에로드 된 어셈블리에서 생성되었음을 알았습니다.

Markus Olsson은 우수 사례를 here이라고했지만 제네릭에 적용하는 방법을 알지 못합니다.

답변

7

구문 분석을 수행 한 후에는 Type.GetType(string)을 사용하여 관련된 유형에 대한 참조를 얻은 다음 Type.MakeGenericType(Type[])을 사용하여 필요한 특정 제네릭 유형을 구성하십시오. 그런 다음 Type.GetConstructor(Type[])을 사용하여 특정 제네릭 형식에 대한 생성자에 대한 참조를 가져오고 마지막으로 ConstructorInfo.Invoke을 호출하여 개체의 인스턴스를 가져옵니다. 당신은 VB.NET로 번역 괜찮다면

Type t1 = Type.GetType("MyCustomGenericCollection"); 
Type t2 = Type.GetType("MyCustomObjectClass"); 
Type t3 = t1.MakeGenericType(new Type[] { t2 }); 
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes); 
object obj = ci.Invoke(null); 
1

, 이런 일이

foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) 
{ 
    // find the type of the item 
    Type itemType = assembly.GetType("MyCustomObjectClass", false); 
    // if we didnt find it, go to the next assembly 
    if (itemType == null) 
    { 
     continue; 
    } 
    // Now create a generic type for the collection 
    Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);; 

    IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType); 
    break; 
} 
관련 문제