a.toraby
a.toraby

Reputation: 3391

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.

Upvotes: 1

Views: 227

Answers (1)

Selman Genç
Selman Genç

Reputation: 101701

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.

Upvotes: 6

Related Questions