如何从 C# 中的字符串创建实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/648160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:40:59  来源:igfitidea点击:

How do I create an instance from a string in C#?

c#reflection

提问by Ben S

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.

我正在从 XML 中读取信息,其中包含我需要实例化的对象类型及其构造函数参数。

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

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

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?

我怎样才能做到这一点?

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

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

采纳答案by Jon Skeet

  • 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().
  • 您需要将完整的类型名称指定为Type.GetType(),包括命名空间,例如“Company.Project2.Type”
  • 如果类型不在同一个程序集(或 mscorlib)中,您还需要提供程序集名称,如果它是强类型的,则包括版本信息。例如,对于非强类型程序集Company.Project2.dll,您可以指定“Company.Project2.Type, Company.Project2”。
  • 要调用带参数的构造函数,您可以调用Activator.CreateInstance(Type, Object[])或获取所需的确切构造函数Type.GetConstructor(),然后调用ConstructorInfo.Invoke().

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

如果这没有帮助,请提供更多信息。

回答by brian chandley

If you want to create a type dynamically at run time, Activator.CreateInstance Method will do it for you. If you issue is with the type having a constructor with parameters, this overload will do this. For example, http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

如果你想在运行时动态创建一个类型,Activator.CreateInstance 方法会为你做。如果您的问题是具有带参数的构造函数的类型,则此重载将执行此操作。例如, http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

I advise looking through the overloads for the best match.

我建议查看重载以获得最佳匹配。

The namespace issue should be not be relavant - as long as the dll is in the bin directory or the GAC you should be OK. The rules may change if the assembly is Strongly named though.

命名空间问题不应该是相关的 - 只要 dll 在 bin 目录或 GAC 中,你应该没问题。如果程序集是强命名的,则规则可能会更改。

Could you provide a code snippiet of the code that is not working (using the method you linked to)? This + the errors you are seeing will be very helpful! [update] Quick sample using the Activator.CreateInstance that handles Constructors w/ paramaters.

您能否提供不起作用的代码的代码片段(使用您链接到的方法)?这+您看到的错误将非常有帮助![更新] 使用 Activator.CreateInstance 处理带参数的构造函数的快速示例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseProduct b =(BaseProduct)System.Activator.CreateInstance(Type.GetType("ConsoleApplication1.Product")
                ,new object[]{typeof(string)}, 
                new object[]{"123"}
            );
            //Activator..::.CreateInstance Method (Type, array<Object>[]()[], array<Object>[]()[])
        }
    }
    public class Product: BaseProduct{
        public  Product(string id) { 

        }
        public string Id {get;set;}


   }

    public abstract class BaseProduct {
        abstract public string Id { get; set; }
    }
}