Attribute.IsDefined doesn't see attributes applied with MetadataType class

后端 未结 4 624
旧巷少年郎
旧巷少年郎 2020-12-03 01:35

If I apply attributes to a partial class via the MetadataType attribute, those attributes are not found via Attribute.IsDefined(). Anyone know why, or what

4条回答
  •  误落风尘
    2020-12-03 02:17

    My solution for generic use. Get the attribute the property that you are looking for. Return null if not found.

    If found, it returns the attribute itself. So you can have access to the properties inside the attribute if you wihs.

    Hopes this help.

    public static Attribute GetAttribute(this PropertyInfo PI, T t) where T: Type
    {
        var Attrs = PI.DeclaringType.GetCustomAttributes(typeof(MetadataTypeAttribute), true);
        if (Attrs.Length < 1) return null;
    
        var metaAttr = Attrs[0] as MetadataTypeAttribute;
        var metaProp = metaAttr.MetadataClassType.GetProperty(PI.Name);
        if (metaProp == null) return null;
    
        Attrs = metaProp.GetCustomAttributes(t, true);
        if (Attrs.Length < 1) return null;
        return Attrs[0] as Attribute;
    }
    

提交回复
热议问题