繁体   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