簡體   English   中英

反射以創建給定類型的程序集

[英]Reflection to create an assembly of a given type

我正在嘗試從字符串獲取類類型。 我覺得我可能會做很多事情,但這是我到目前為止的代碼:

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))

我得到的錯誤是:

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

因此,程序集在錯誤時已經在內存中。 不能使用反射來加載已經在內存中的程序集嗎? 有沒有一種方法可以使用反射加載而不使用Assembly.Load(...

編輯:

感謝@stakx的建議,我終於想到了:

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

假設您的項目未引用包含ITest的程序集,則獲取與typeof(ITest)等效的Type對象的最簡單方法可能是通過靜態Type.GetType方法

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

(如果在項目中引用該程序集,則只需設置t = typeof(FooNamespace.ITest) 。)

然后繼續關閉您的通用方法:

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

您可以得到如下類型:

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

然后使用激活器獲取您的實例:

Activator.CreateInstance(type);

使用AssemblyQualifiedName是最簡單的方法,但是如果您的類在正在執行的程序集中,則namespace.ClassName將可以正常工作。

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

從這一點來看,您可以使用“事物”,就像使用“ namespace.ClassName”的實例一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM