反射 - 在属性上获取属性名称和值 [英] Reflection - get attribute name and value on property

查看:24
本文介绍了反射 - 在属性上获取属性名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我们称之为 Book,它有一个名为 Name 的属性.有了这个属性,我就有了一个与之关联的属性.

I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.

public class Book
{
    [Author("AuthorName")]
    public string Name
    {
        get; private set; 
    }
}

在我的主要方法中,我使用反射并希望获得每个属性的每个属性的键值对.因此,在此示例中,我希望看到属性名称为Author",属性值为AuthorName".

In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.

问题:如何使用反射获取属性的属性名称和值?

Question: How do I get the attribute name and value on my properties using Reflection?

推荐答案

使用 typeof(Book).GetProperties() 来获取 PropertyInfo 实例的数组.然后在每个 PropertyInfo 上使用 GetCustomAttributes() 来查看它们中是否有任何一个具有 Author 属性类型.如果有,您可以从属性信息中获取属性名称,并从属性中获取属性值.

Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.

沿着这些方向扫描具有特定属性类型的属性的类型并返回字典中的数据(请注意,这可以通过将类型传递到例程中而变得更加动态):

Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):

public static Dictionary<string, string> GetAuthors()
{
    Dictionary<string, string> _dict = new Dictionary<string, string>();

    PropertyInfo[] props = typeof(Book).GetProperties();
    foreach (PropertyInfo prop in props)
    {
        object[] attrs = prop.GetCustomAttributes(true);
        foreach (object attr in attrs)
        {
            AuthorAttribute authAttr = attr as AuthorAttribute;
            if (authAttr != null)
            {
                string propName = prop.Name;
                string auth = authAttr.Name;

                _dict.Add(propName, auth);
            }
        }
    }

    return _dict;
}

这篇关于反射 - 在属性上获取属性名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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