使用反射检索属性值
假设我们有一个类,其属性带有元数据,我们希望通过反射检索属性名称和值。例如,该类有一个名为Name
的属性,并关联了一个Author
属性。
我们可以使用typeof(Book).GetProperties()
来检索Book
类的属性信息。对于每个属性,我们使用GetCustomAttributes()
来检查与所需类型(例如Author
属性)匹配的属性。
一旦找到Author
属性,我们就可以从PropertyInfo
实例中获取属性名称,并从属性本身获取属性值。 以下代码实现扫描类型、识别带有Author
属性的属性,并生成包含属性详细信息的字典:
public static Dictionary<string, string> GetAuthors() { var _dict = new Dictionary<string, string>(); var props = typeof(Book).GetProperties(); foreach (var prop in props) { var attrs = prop.GetCustomAttributes(true); foreach (var attr in attrs) { var authAttr = attr as AuthorAttribute; if (authAttr != null) { var propName = prop.Name; var auth = authAttr.Name; _dict.Add(propName, auth); } } } return _dict; }
此方法能够在运行时检索具有特定属性的属性的属性名称和值。
以上是如何使用C#中的反射检索属性属性和值?的详细内容。更多信息请关注PHP中文网其他相关文章!