简体   繁体   English

类型对象的运行时转换

[英]Runtime Casting of the Type Object

I'd like to instantiate an object of a generic class during run-time; 我想在运行时实例化泛型类的对象; I call a method which gives me back a Type Object; 我调用了一个方法,该方法可以给我返回类型对象。 I'd like to convert this generic class into a specific class, and then instantiate objects of this class. 我想将此泛型类转换为特定类,然后实例化该类的对象。 Is it possible? 可能吗? I used to write in Java: 我曾经用Java编写过:

Class<DBConnectionProvider> dBConnectionProviderClass =
              (Class<DBConnectionProvider>)Configuration.getInstance().getDbConnectionProviderClass();

The method getDbConnectionProviderClass() returns a Class Object which is converted on run-time; 方法getDbConnectionProviderClass()返回一个在运行时转换的Class对象。 In my C# application this method returns a Type object; 在我的C#应用​​程序中,此方法返回Type对象。 is it possible to convert this in DBConnectionProvider and instantiate a class of this? 是否可以在DBConnectionProvider中将其转换并实例化此类? Thank you for your answers. 谢谢您的回答。

Once you have the type object you just need to call: 一旦有了类型对象,您只需要调用:

object o = Activator.CreateInstance([your type]).Unwrap();

or if you need to supply constructor arguments: 或者如果您需要提供构造函数参数:

object o = Activator.CreateInstance([your type], obj1,obj2...).Unwrap();

And then cast to your type. 然后转换为您的类型。

Simple example of creating instances of classes with reflection (Java) 使用反射创建类实例的简单示例(Java)

import java.awt.Rectangle;

public class SampleNoArg {

   public static void main(String[] args) {
      Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
      System.out.println(r.toString());
   }

   static Object createObject(String className) {
      Object object = null;
      try {
          Class classDefinition = Class.forName(className);
          object = classDefinition.newInstance();
      } catch (InstantiationException e) {
          System.out.println(e);
      } catch (IllegalAccessException e) {
          System.out.println(e);
      } catch (ClassNotFoundException e) {
          System.out.println(e);
      }
      return object;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM