通过反射在运行时实例化一个类
您好,我正在尝试在运行时发现并实例化一个类。程序集被加载到工厂对象中。
到目前为止它工作正常
Object obj = Activator.CreateInstance(
(factory.ProxyAssembly.GetType("tempuri.org.Authorizations")));
,但我无法使用 obj
获取属性名称,因为 Obj.FirstName
或 obj.LastName
不可用,所以我尝试将其类型转换为适当的底层类。
但下面给出的代码不起作用。
factory.ProxyAssembly.GetType("tempuri.org.Authorizations")
.UnderlyingSystemType.BaseType a =
Activator.CreateInstance(factory.ProxyAssembly
.GetType("tempuri.org.Authorizations").UnderlyingSystemType);
任何帮助表示赞赏。
Hello I am trying to discover and instantiate a class at run time. The Assembly is loaded in factory object.
It works fine till this point
Object obj = Activator.CreateInstance(
(factory.ProxyAssembly.GetType("tempuri.org.Authorizations")));
but I can not get property name with obj
as Obj.FirstName
or obj.LastName
is not available so I am trying to typecast it to a proper underlying class.
But the below given code does not work.
factory.ProxyAssembly.GetType("tempuri.org.Authorizations")
.UnderlyingSystemType.BaseType a =
Activator.CreateInstance(factory.ProxyAssembly
.GetType("tempuri.org.Authorizations").UnderlyingSystemType);
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法进行转换,您没有将程序集添加为项目中的参考。您需要使用反射来获取对象属性。使用 Type.GetProperty 和 PropertyInfo.GetValue。请注意,建议使用 C# 版本 4 dynamic 关键字如何显着减轻语法痛苦。
You cannot cast, you don't have the assembly added as a reference in your project. You need to use Reflection to get the object properties. Use Type.GetProperty and PropertyInfo.GetValue. Note how the C# version 4 dynamic keyword can lessen the syntax pain considerably, recommended.
使用(类型)查看铸造。其中 Type 是返回的类类型。在这种情况下,类型是编译时的事情。反射使用抽象来屏蔽具体类型,但在这种情况下您将需要它。除非你使用 do:
Look into casting with (Type). Where Type is class type that comes back. Type is a compile time thing in that case. Reflection uses abstractions to shield the concrete type, but in that case you would need it. Unless you use do:
您需要在实例化对象后对其进行强制转换。
You need to cast the object after instantiating it.