![](/img/trans.png)
[英]Instantiating a class from different .dll using reflection based on the class name?
[英]Instantiating a class in the same .dll using reflection based on the class name?
这应该很简单,但是我找不到任何可以告诉我如何执行此操作的地方。 我有一个类,它与我正在使用的同一个dll中。
我只想做类似的事情。
thing.InstanceClass("ClassName");
我不想这样做:
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
那是因为我想使用反射实例化的类在同一程序集中。
Type instanceType = Type.GetType("SomeNamespace.SomeType");
object instance = Activator.CreateInstance(instanceType);
如果程序集已经加载到AppDomain中,则可以通过Type.GetType(...)
解析它。
如果需要装配,则可以使用Assembly.GetEntryAssembly
,也可以使用typeof(SomeType).Assembly
,其中SomeType
在目标装配中。
我相信System.Activator.CreateInstance是您寻求的框架方法。
如果它是项目中的已知(引用的,不是COM等)类型,那么最好的方法是使用强类型的CreateInstance
函数:
MyClass instance = Activator.CreateInstance<MyClass>();
由于没有装箱/拆箱,这将节省很多性能成本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.