简体   繁体   English

加载Assembly并使用Reflection创建类

[英]Load Assembly and create class using Reflection

I could not find a way of creating a class object from given type and assembly definition using reflection. 我找不到一种使用反射从给定类型和程序集定义创建类对象的方法。 For my case, I have a string containing class and assembly name and need to create the object: 就我而言,我有一个包含类和程序集名称的字符串,需要创建该对象:

string str = "My.Assembly.Namesapce.MyClass, My.Assembly.Namesapce, Version=4.0.0.0, Culture=neutral, PublicKeyToken=84474dc3c6524430";
var objClass = --SOME CODE TO USE  STR AND CREATE MyClass--

I have tried to split and create class but that is not very good way of doing it. 我试图拆分并创建类,但这不是很好的方法。

Type type = Type.GetType(str);
object objClass = Activator.CreateInstance(type);

however, to do anything useful with the object you will have to use a common interface / base-class, reflection, or dynamic . 但是,要对对象执行任何有用的操作,您将必须使用公共接口/基类,反射或dynamic

Note: if you can type the variable as MyClass objClass , then the simpler version is of course: 注意:如果您可以将变量键入为MyClass objClass ,则当然是更简单的版本:

MyClass objClass = new MyClass();

You need to do two things: 您需要做两件事:

1) Convert your string str into a type, and 2) Create an instance of that type. 1)将您的字符串str转换为类型,然后2)创建该类型的实例。

string typeString = "My.Assembly.Namesapce.MyClass, My.Assembly.Namesapce, Version=4.0.0.0, Culture=neutral, PublicKeyToken=84474dc3c6524430";

// Get a reference to the type.
Type theType = Type.GetType(typeString, true, false);

// Create an instance of that type.
MyClass  theInstance = (MyClass)Activator.CreateInstance(theType);

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

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