简体   繁体   English

在设计时不知道类名创建对象

[英]Creating an object without knowing the class name at design time

Using reflection, I need to investigate a user DLL and create an object of a class in it. 使用反射,我需要调查用户DLL并在其中创建一个类的对象。

What is the simple way of doing it? 这样做的简单方法是什么?

System.Reflection.Assembly is the class you will want to use. System.Reflection.Assembly是您要使用的类。 It contains many method for iterating over the types contained with a user DLL. 它包含许多用于迭代用户DLL包含的类型的方法。 You can iterate through each class, perhaps see if it inherits from a particular interface etc. 您可以遍历每个类,也许看看它是否继承自特定的接口等。

http://msdn.microsoft.com/en-us/library/system.reflection.assembly_members.aspx http://msdn.microsoft.com/en-us/library/system.reflection.assembly_members.aspx

Investigate Assembly.GetTypes() method for getting the list of types, or Assembly.GetExportedTypes() for the public ones only. 调查Assembly.GetTypes()用于获取类型列表的方法,或Assembly.GetExportedTypes()只为公立。

您可以使用Activator.CreateInstance从Type对象创建类的实例,以获取可以使用Assembly.GetTypes的dll中的所有类型

Take a look at these links: 看看这些链接:

http://www.java2s.com/Code/CSharp/Development-Class/Createanobjectusingreflection.htm http://www.java2s.com/Code/CSharp/Development-Class/Createanobjectusingreflection.htm

http://msdn.microsoft.com/en-us/library/k3a58006.aspx http://msdn.microsoft.com/en-us/library/k3a58006.aspx

You basically use reflection to load an assembly, then find a type you're interested in. Once you have the type, you can ask to find it's constructors or other methods / properties. 你基本上使用反射加载一个程序集,然后找到你感兴趣的类型。一旦你有了这个类型,你可以要求找到它的构造函数或其他方法/属性。 Once you have the constructor, you can invoke it. 一旦有了构造函数,就可以调用它。 Easy! 简单!

As it has already been said, you need to poke the System.Reflection namespace. 正如已经说过的那样,你需要戳一下System.Reflection命名空间。

If you know in advance the location/name of the DLL you want to load, you need to iterate through the Assembly.GetTypes(). 如果事先知道要加载的DLL的位置/名称,则需要遍历Assembly.GetTypes()。

In Pseudocode it would look something like this: 在Pseudocode中,它看起来像这样:

Create and assembly object. 创建和组装对象。

Iterate through all the types contained in the assembly. 遍历程序集中包含的所有类型。

Once you find the one you are looking for, invoke it (CreateInstance)… 找到您要找的那个后,调用它(CreateInstance)......

Use it wisely. 明智地使用它。

;) ;)

I have plenty of Reflection code if you want to take a look around, but the task is really simple and there are at least a dozen of articles with samples out there in the wild. 如果你想环顾四周,我有很多反射代码,但任务非常简单,并且至少有十几篇文章在野外有样本。 (Aka Google). (阿卡谷歌)。 Despite that, the MSDN is your friend for Reflection Reference. 尽管如此,MSDN是您参与Reflection Reference的朋友。

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

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