繁体   English   中英

通过反射在运行时实例化一个类

[英]Instantiate a class at runtime through reflection

您好我正在尝试在运行时发现并实例化一个类。 装配在工厂对象中加载。

它一直工作到这一点

Object obj = Activator.CreateInstance(
   (factory.ProxyAssembly.GetType("tempuri.org.Authorizations")));

但我无法使用obj获取属性名称,因为Obj.FirstNameobj.LastName不可用,所以我试图将其类型转换为正确的底层类。

但是下面给出的代码不起作用。

 factory.ProxyAssembly.GetType("tempuri.org.Authorizations")
     .UnderlyingSystemType.BaseType a = 
         Activator.CreateInstance(factory.ProxyAssembly
              .GetType("tempuri.org.Authorizations").UnderlyingSystemType);

任何帮助表示赞赏。

tempuri.org.Authorizations a =  (tempuri.org.Authorizations)Activator.CreateInstance(factory.ProxyAssembly.GetType("tempuri.or g.Authorizations");

查看使用( 类型 )进行转换。 其中Type是返回的类类型。 在这种情况下,Type是编译时的事情。 Reflection使用抽象来屏蔽具体类型,但在这种情况下你需要它。 除非你使用do:

a.getClass().getField("FirstName").getString(a);

您无法强制转换,您没有在项目中添加程序集作为参考。 您需要使用Reflection来获取对象属性。 使用Type.GetProperty和PropertyInfo.GetValue。 请注意C#版本4 动态关键字如何能够大大减轻语法上的痛苦,建议使用。

您需要在实例化后转换对象。

暂无
暂无

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

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