2013-08-19 4 views
1

어셈블리에서 해당 이름을 모른 채 클래스를로드하려고합니다 (Class1 : Interface라고 말합니다). 내 코드는 다음과 같습니다의 I 온라인으로 발견 기사와 MSDN을 바탕으로C#에서 클래스를 동적으로로드하십시오

Assembly a = Assembly.LoadFrom("MyDll.dll"); 
Type t = (Type)a.GetTypes()[0]; 
(Interface) classInstance = (Interface) (ClasActivator.CreateInstance(t); 

, GetTypes()[0]이 클래스 1을 반환한다고 가정한다 (MyDll.dll에서 하나의 클래스가있다). 그러나 내 코드는 Class1.Properties.Settings을 반환합니다. 그래서 3 행은 예외를 만듭니다.

Unable to cast object of type 'Class1.Properties.Settings' to type Namespace.Interface'. 

저는이 문제를 해결하는 이유와 방법을 정말로 모릅니다.

Type t = a.GetTypes() 
    .FirstOrDefault(type => type.GetInterface(typeof(Interface).FullName) != null); 
+0

수행하려는 작업에 따라 원래 인터페이스에 속성으로 태그를 지정한 다음 해당 속성이있는 모든 유형을 확인할 수 있습니다. – Blam

답변

3

하나 개 이상의 유형을 (당신은 가능성이 DLL에 Settings.settings 파일을 저장할 수있는 조립, 그것은이에 후드 클래스를 만듭니다

+0

매력처럼 작동했습니다! Thx – Unplug

+0

@Martin [대신에 답변을 받아 들일 수있는 방법에 대해] 감사의 말 대신에 (http://stackoverflow.com/help/someone-answers) –

2

그냥 인터페이스를 구현하는 첫 번째를 찾을 수 확인 Settings.Designer.cs 파일), 코드에서 첫 번째 클래스 만 얻었다면이 경우 Settings 클래스로 밝혀 졌기 때문에 모든 유형을 거쳐 필요한 인터페이스가있는 클래스를 검색해야합니다.

Assembly asm = Assembly.LoadFrom("MyDll.dll"); 
Type[] allTypes = asm.GetTypes(); 
foreach (Type type in allTypes) 
{ 
    // Only scan objects that are not abstract and implements the interface 
    if (!type.IsAbstract && typeof(IMyInterface).IsAssignableFrom(type)); 
    { 
     // Create a instance of that class... 
     var inst = (IMyInterface)Activator.CreateInstance(type); 

     //do your work here, may be called more than once if more than one class implements IMyInterface 
    } 
} 
+1

'Single'의 사용을 권장 할 수 있습니다. 왜냐하면 어셈블리에 그러한 클래스가 하나 뿐인 것처럼 보이기 때문입니다. –

관련 문제