Custom attribute on property - Getting type and value of attributed property

后端 未结 4 1830
日久生厌
日久生厌 2020-11-29 04:20

I have the following custom attribute, which can be applied on properties:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class Id         


        
4条回答
  •  忘掉有多难
    2020-11-29 04:44

    Something like the following,, this will use only the first property it comes accross that has the attribute, of course you could place it on more than one..

        public object GetIDForPassedInObject(T obj)
        {
            var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                       .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1);
            object ret = prop !=null ?  prop.GetValue(obj, null) : null;
    
            return ret;
        }  
    

提交回复
热议问题