反射 - 获取属性的属性名称和值

2023-11-26

我有一个类,我们将其称为“Book”,其属性名为“Name”。有了这个属性,我就有了一个与之关联的属性。

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

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

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


Use typeof(Book).GetProperties()得到一个数组PropertyInfo实例。然后使用GetCustomAttributes()在各个PropertyInfo看看他们中是否有人有Author属性类型。如果是,您可以从属性信息中获取属性名称,并从属性中获取属性值。

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

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

反射 - 获取属性的属性名称和值 的相关文章

随机推荐