[英]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.