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

查看:9
本文介绍了如何从 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.

我该怎么做?

未在项目属性中正确设置程序集名称和默认命名空间.

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

推荐答案

  • 您需要为 Type.GetType(),包括命名空间,例如"公司.项目2.类型"
  • 如果类型不在同一个程序集(或 mscorlib)中,您还需要提供程序集名称,如果它是强类型的,则包括版本信息.例如,对于非强类型程序集 Company.Project2.dll,您可以指定Company.Project2.Type, Company.Project2".
  • 要调用带参数的构造函数,您可以调用 Activator.CreateInstance(键入,Object[]) 或使用 Type.GetConstructor() 然后调用 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天全站免登陆