简体   繁体   中英

How to Get Property Value from a type defined in an Assembly?

This is the code (I've modified it for simplicity):

System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
Type t = asm.GetType("OneSubClass");
System.Reflection.PropertyInfo pi = t.GetProperty("SubClassProperty");

After this code, asm is my application's exe, which has a half dozen or so classes inside it.

t is the type for one of those classes inside the exe.

pi is filled with the property info of the property within the class OneSubClass

When running my application, it creates instances for all these classes defined in the exe. Then the above code is executed. However, how do I get the actual value of the property?

If I try something like:

pi.GetValue(asm, null);

it gives me exception "object does not match target type" - I need an instance of the class I want the property from (which I'm not sure how to get - I only have asm )

You need an instance of the OneSubClass class. The class (and the type) itself is just a template - it has no values for any of its properties. Each instance of the type has values, and you pass the instance into GetValue :

pi.GetValue(instanceOfOneSubClass, null);

One way to create an instance is using Activator :

object myInstance = Activator.CreateInstance(typeof(OneSubClass));

But that is basically the equivalent of calling new OneSubClass() , so unless you know the default constructor will do exactly what you're expecting here, that's not always very useful.

When running my application, it creates instances for all these classes defined in the exe.

I'm not exactly sure what this means. Are you saying somewhere there is already a created instance and you need to somehow get a handle to it?

t is only a type, not an instance of that type.

You first have to create an instance of that type like this:

object asmInstance = Activator.CreateInstance(t);

then get the value on that instance

pi.GetValue(asmInstance, null);

You are triying to get the property from the Assembly class you are instantiating.

To retrieve a value from an object, you need the reference to that object:

object GetValueFromClass(object Class)
{

    System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
    Type t = asm.GetType("OneSubClass");
    System.Reflection.PropertyInfo pi = t.GetProperty("SubClassProperty");

    return pi.GetValue(Class, null);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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