Hello I am trying to discover and instantiate a class at run time. The Assembly is loaded i开发者_运维技巧n 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.
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.
tempuri.org.Authorizations a = (tempuri.org.Authorizations)Activator.CreateInstance(factory.ProxyAssembly.GetType("tempuri.or g.Authorizations");
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:
a.getClass().getField("FirstName").getString(a);
You need to cast the object after instantiating it.
精彩评论