简体   繁体   中英

How to reflect a class from its property value?

Lets suppose, we have these three types:

class class1{ public static int serial=1};
class class2{ public static int serial=2};
class class3{ public static int serial=3};

The serial could be a static field or a property like:

class class1{ public override byte serial {get{return 0x01; }}};

In my application I receive the serial value from somewhere and need to reflect the appropriate class. Is that possible to reflect any of these types using the serial field of that item? Do I have to create a map table between serial id and class name to find the related class name for reflection? Or System.Reflection allows me to find the class directly from its field or property value ? I think it would be a better way because We do not need to edit the table for new types.
Thanks for any help.

Yes, you can get the type by the field's value:

var type = Assembly.GetExecutingAssembly()
           .GetTypes()
           .FirstOrDefault(x => x.GetField("serial") != null && 
                               (int)x.GetField("serial").GetValue(null) == 2)

If the types are defined in another assembly rather than the currently executing assembly then you need to first get that assembly using the methods in Assembly class (like Load , LoadFrom , LoadFile ).

And also fields should be static in order this to work, otherwise you need an instance to get field value and pass it to GetValue method instead of 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