【问题标题】:In C#, how to create an object given the name of its type? [duplicate]在 C# 中,如何创建一个给定其类型名称的对象? [复制]
【发布时间】:2011-01-20 08:21:07
【问题描述】:

我知道我需要实例化的对象的类型(比如 IAnimal)和名称(比如 Tiger)。假设知道对象名称的变量是一个字符串,我该如何编写代码来实例化 Tiger。我可能在这里遗漏了一些简单的东西,但目前我一直坚持这一点。

更新:我的意思是 Class Tiger : IAnimal,上面进行了更改以反映这一点。

【问题讨论】:

    标签: c# types type-conversion casting typeof


    【解决方案1】:

    使用Activator.CreateInstance 方法

    示例:

    // the string name must be fully qualified for GetType to work
    string objName = "TestCreateInstance.MyObject";
    IProcess txObject = (IProcess)Activator.CreateInstance(Type.GetType(objName));
    

    object o = Activator.CreateInstance("Assem1.dll", "Friendly.Greeting");
    

    另见:Reflection Examples C#

    【讨论】:

      【解决方案2】:

      我不确定我是否完全理解这个问题。然而,假设 ITiger 实际上是一个具体的类而不是一个接口(正如我*所建议的那样)。

      您可以使用反射从字符串创建类型的实例。

      类似:

      ITiger myTiger = Activator.CreateInstance("ITiger") as ITiger;
      

      http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

      这就是你要问的吗?

      【讨论】:

        【解决方案3】:

        使用反射通过类型名称实例化一个类的对象。

        object o = Activator.CreateInstance(Type.GetType("Tiger"));
        

        请注意,您不能实例化接口(根据您的命名来判断),因为它们只是定义特定类应该实现什么的契约。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-24
          • 2011-01-27
          • 2013-03-23
          相关资源
          最近更新 更多