2014-09-16 1 views
0

문자열에서 클래스 유형을 가져 오려고합니다. 나는 이것에 대해 먼 길을 갈 수 느끼지만, 이것은 내가 지금까지 가지고있는 코드 :주어진 유형의 어셈블리를 만들기위한 리플렉션

A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll 

그래서 이미 조립이 있습니다

System.Reflection.MethodInfo method = typeof(MyClass).GetMethod("MyFunc"); 

string myInterfaceId = "ITest"; 
Type myType = _type; // This is a WPF App that ultimately calls this process 
         // Debugger shows that _is correctly populated 

AssemblyName an = new AssemblyName(myType.AssemblyQualifiedName); // Error here 
Assembly a = Assembly.Load(an); 

System.Reflection.MethodInfo generic = method.MakeGenericMethod(
       a.GetType(myInterfaceId)) 

내가 오류입니다 오류가 발생한 지점의 메모리. 리플렉션을 사용하여 이미 메모리에있는 어셈블리를로드 할 수 있습니까? Assembly.Load(...을 사용하지 않고 리플렉션을로드하는 방법이 있습니까?

이 편집 :

덕분에 제안을 @stakx하기 위해, 나는 마침내이 함께했다 :

var meInterfaceType = myType.GetTypeInfo().Assembly.DefinedTypes.FirstOrDefault(k => k.Name == myInterfaceId) 
+0

작동하지 않는 코드를 볼 수 있습니다. 그러나 실제로 무엇을하고 싶습니까? 왜 그 어셈블리를로드하고 싶습니까? 너는 그걸로 무엇을 할거니? 그것은 당신이 말한 것처럼 이미 우회를하고있을 수도 있으므로 이상적으로 우리는 당신이 우회로가는 것이 아니라 가장 쉬운 방법으로 목표를 달성하도록 도울 것입니다. – stakx

답변

0

프로젝트 ITest이 들어있는 어셈블리를 참조하지 않는 것으로 가정하면, 가장 쉬운 방법은 Type 개체를 얻을 수 있습니다 당신이 다시 인 경우 (

// you need to specify the assembly-qualified name of your type parameter type: 
var t = Type.GetType("FooNamespace.ITest, FooAssembly, Version=…, PublicKeyToken=…"); 

: typeof(ITest)에 해당이 static Type.GetType method를 통해 수 있습니다 프로젝트에서 해당 어셈블리를 ferencing, 단순히 t = typeof(FooNamespace.ITest) 설정)

이 그런 다음 일반적인 방법 닫는 진행 :.

var type = Type.GetType("MyString"); 

그런 다음에 활성제를 사용

var openMethod = typeof(MyClass).GetMethod("MyFunc"); // as before 
var closedMethod = openMethod.MakeGenericMethod(t); 
+0

고마워요. - 이것이 내 문제를 직접 해결하지는 않았지만, 내 길을 올바른 길로 인도했습니다 (최종 해결책을위한 편집 참조) –

0

당신은 같은 종류를 얻을 수 있습니다 인스턴스를 얻으십시오 :

Activator.CreateInstance(type); 
0

AssemblyQualifiedName은 가장 바보 같은 문자열이지만 클래스가 실행중인 어셈블리에 있으면 namespace.ClassName이 정상적으로 작동합니다. 당신이 "namespace.ClassName"의 인스턴스를 사용하는 것처럼이 시점에서

var type = Type.GetType("AssemblyQualifiedNameOfTheClass or namespace.ClassName"); 
var thing = (MyClass)Activator.CreateInstance(type); 

, 당신은 "일을"사용할 수 있습니다.

관련 문제