如何从其属性值反映一个类? [英] How to reflect a class from its property value?

查看:25
本文介绍了如何从其属性值反映一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我们有这三种类型:

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; }}};

在我的应用程序中,我从某处接收序列值并需要反映适当的类.是否可以使用该项目的序列字段来反映这些类型中的任何一种?我是否必须在序列号和类名之间创建一个映射表才能找到相关的类名进行反射?或者 System.Reflection 允许我直接从其字段或属性值中找到该类?我认为这会是一个更好的方法,因为我们不需要为新类型编辑表格.
感谢您的帮助.

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)

如果类型是在另一个程序集中而不是当前正在执行的程序集中定义的,那么您需要首先使用 Assembly 类中的方法(如 LoadLoadFrom, LoadFile).

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).

而且字段也应该是 static 以便它工作,否则你需要一个实例来获取字段值并将其传递给 GetValue 方法而不是 null.

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.

这篇关于如何从其属性值反映一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆