Check if property has attribute

前端 未结 8 1552
刺人心
刺人心 2020-11-28 03:03

Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:

    [IsNotNullable]
    [I         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 03:29

    There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

    var t = typeof(YourClass);
    var pi = t.GetProperty("Id");
    var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));
    

    If you need to retrieve attribute properties then

    var t = typeof(YourClass);
    var pi = t.GetProperty("Id");
    var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
    if (attr.Length > 0) {
        // Use attr[0], you'll need foreach on attr if MultiUse is true
    }
    

提交回复
热议问题