我如何在C#中的字符串创建一个实例? [英] How do I create an instance from a string in C#?

查看:339
本文介绍了我如何在C#中的字符串创建一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从其中包含一个对象,我需要它的构造函数的参数来实例沿的类型的XML读取信息。

I'm reading information from an XML which contains the type of an object that I need to instantiate along with it's constructor parameters.

对象类型实际上是在另一个项目中,兄弟姐妹命名空间内。 (我需要创建Company.Project1类中的一个Company.Project2.Type。)

The object type is actually in another project, within a sibling namespace. (I need to create a Company.Project2.Type within Company.Project1 class.)

我发现这个问题,但它不处理构造函数的参数或一个事实,即它在另一个命名空间。

I found this question, but it doesn't handle the constructor parameters or the fact that it's in another namespace.

我怎样才能做到这一点?

How can I do this?

编辑:程序集名称和默认命名空间并没有在项目属性中设置正确

The assembly name and default namespace wasn't set correctly in the project properties.

推荐答案


  • 您需要指定完整的类型名称 Type.GetType() ,包括名字空间,例如Company.Project2.Type

  • 如果该类型不在同一个组件(或mscorlib程序),你需要给程序集的名称也包括版本信息,如果它是强类型。例如,对于非强类型组装 Company.Project2.dll ,您可以指定Company.Project2.Type,Company.Project2。

  • 要调用构造函数与您可以调用 Activator.CreateInstance参数(类型,对象[]) 或得到你想要的精确构造<一个href=\"http://msdn.microsoft.com/en-us/library/system.type.getconstructor.aspx\"><$c$c>Type.GetConstructor()然后调用<一个href=\"http://msdn.microsoft.com/en-us/library/system.reflection.constructorinfo.invoke.aspx\"><$c$c>ConstructorInfo.Invoke().

  • You need to specify the full type name to Type.GetType(), including namespace, e.g. "Company.Project2.Type"
  • If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly Company.Project2.dll, you might specify "Company.Project2.Type, Company.Project2".
  • To call a constructor with parameters you can call Activator.CreateInstance(Type, Object[]) or get the exact constructor you want with Type.GetConstructor() and then call ConstructorInfo.Invoke().
  • 如果没有帮助,请给出更多的信息。

    If that doesn't help, please give more information.

    这篇关于我如何在C#中的字符串创建一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆