简体   繁体   English

使用基于类名的反射实例化同一.dll中的类?

[英]Instantiating a class in the same .dll using reflection based on the class name?

This should be simple but I can't find anywhere that tells me how to do this. 这应该很简单,但是我找不到任何可以告诉我如何执行此操作的地方。 I've got a class, it's in the same dll as the one I am using to do this. 我有一个类,它与我正在使用的同一个dll中。

All I want to do is something like. 我只想做类似的事情。

thing.InstanceClass("ClassName");

I would like to do this without doing: 我不想这样做:

Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");

And that is because the classes I would like to instance using reflection are in the same assembly. 那是因为我想使用反射实例化的类在同一程序集中。

Type instanceType = Type.GetType("SomeNamespace.SomeType");
object instance = Activator.CreateInstance(instanceType);

You can resolve it through Type.GetType(...) if the assembly is already loaded into the AppDomain. 如果程序集已经加载到AppDomain中,则可以通过Type.GetType(...)解析它。

If you need the assembly you can use Assembly.GetEntryAssembly , or possibly typeof(SomeType).Assembly where SomeType is in your target assembly. 如果需要装配,则可以使用Assembly.GetEntryAssembly ,也可以使用typeof(SomeType).Assembly ,其中SomeType在目标装配中。

我相信System.Activator.CreateInstance是您寻求的框架方法。

If it's a known (referenced, not COM etc.) type within your project, then the best way is to use the strongly-typed CreateInstance function: 如果它是项目中的已知(引用的,不是COM等)类型,那么最好的方法是使用强类型的CreateInstance函数:

MyClass instance = Activator.CreateInstance<MyClass>();

This will save much of performance cost since there is no boxing/unboxing. 由于没有装箱/拆箱,这将节省很多性能成本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM