Get all properties with reflection values

I wrote my own property attribute and set it to a couple of properties in my class. Now I would like that at runtime only properties that have this attribute will be able to get the value of the property, as well as the values ​​of the attribute fields. Could you help me with this task? thanks for the help

+5
source share
3 answers

Here is 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;}
}
+13
source
0
source

All Articles