【问题标题】:How to create object of a class where the class name is stored in string variable in C# [duplicate]如何创建一个类的对象,其中类名存储在C#中的字符串变量中[重复]
【发布时间】:2014-02-21 02:05:04
【问题描述】:

我有一个关于在 c# 中创建类的对象的问题,其中类名存储在字符串变量中

例如。字符串 str="飞行员"

As we create object of the class like this
ClassName objectname=new ClassName();

由于某种原因,我需要使用存储类名的字符串变量而不是 ClassName。

【问题讨论】:

标签: c#


【解决方案1】:

您将使用Type.GetType(string),然后使用Activator.CreateInstance(Type)

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

注意:

  • 类型名称必须包含命名空间,例如Foo.Bar.SomeClassName
  • 除非您指定程序集限定的类型名称,否则Type.GetType(string) 只会查看当前正在执行的程序集和mscorlib。如果您想使用其他程序集,请使用程序集限定名称或改用 Assembly.GetType(string)
  • 假设该类型有一个公共的无参数构造函数
  • 您的变量类型必须是instance,因为变量类型是编译时需要的一部分

【讨论】:

【解决方案2】:

这是一个例子。您可能需要指定完整的命名空间路径。

Namespace.Pilot config = (Namespace.Pilot)Activator.CreateInstance(Type.GetType("Namespace.Pilot"));

【讨论】:

    【解决方案3】:

    您可以使用Reflection 这样做:

    var type = Assembly.Load("MyAssembly").GetTypes().Where(t => t.Name.Equals(str));
    return Activator.CreateInstance(type);
    

    【讨论】:

      【解决方案4】:

      您可以通过使用Activator

      var type = "System.String";
      var reallyAString = Activator.CreateInstance(
              // need a Type here, so get it by type name
              Type.GetType(type), 
              // string's has no parameterless ctor, so use the char array one
              new char[]{'a','b','c'});
      Console.WriteLine(reallyAString);
      Console.WriteLine(reallyAString.GetType().Name);
      

      输出:

      abc
      String
      

      【讨论】:

        猜你喜欢
        • 2013-03-05
        • 2020-10-17
        • 2013-12-13
        • 2013-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多