简体   繁体   English

使用值反射获取所有属性

[英]Get all properties with values reflection

I wrote custom property attribute and set it on couple of properties in my class. 我编写了自定义属性属性并将其设置在我的类中的几个属性上。 Now I would like during runtime get only properties which has this attribute, be able to get value of the property as well as values of attribute fields. 现在我想在运行时只获取具有此属性的属性,能够获取属性的值以及属性字段的值。 Could You please help me with this task ? 你能帮我完成这项任务吗? thanks for help 感谢帮助

Here's an example: 这是一个例子:

void Main()
{
    var myC = new C { Abc = "Hello!" };
    var t = typeof(C);
    foreach (var prop in t.GetProperties())
    {
        var attr = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().FirstOrDefault();
        if (attr != null)
        {
            var attrValue = attr.MaximumLength; // 100
            var propertyValue = prop.GetValue(myC, null); // "Hello!"
        }
    }
}
class C
{
    [StringLength(100)]
    public string Abc {get;set;}
}

您可以使用PropertyInfo.Attributes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM