reflection: private property how to extract custom attribute

浪尽此生 提交于 2020-01-07 03:16:05

问题


Hi it's possible to retrieve custom attribute in private property

   public class TestAttr
    {
        [SaveInState]
        protected string testPrivate { get { return "test private"; }  }
        [SaveInState]
        public string testPublic { get{ return "test public"; }}

        public IDictionary<string, object> dumpVars()
        {

            IDictionary<string, object> dict = new Dictionary<string, object>();

            Type ownerClassType = this.GetType();


            foreach (var mi in ownerClassType.GetProperties(BindingFlags.NonPublic))
            {

                var varAttrib = Attribute.GetCustomAttribute(mi, typeof(SaveInStateAttribute));
                if (varAttrib != null)
                {
                    dict.Add(mi.Name, mi.GetValue(this, null));
                }
            }

            return dict;

        }
    }

thanks


回答1:


Yes, it is perfectly possible. The code you have (while a little pointless since you don't need reflection since you're working in your own type) is pretty close:

var type = this.GetType();
foreach(var prop in 
    type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
    var attr = prop.GetCustomAttributes(typeof(SaveInStateAttribute), true);

    if(attr.Length > 0)
    {
        // Add the attributes to your collection
    }
}


来源:https://stackoverflow.com/questions/5437002/reflection-private-property-how-to-extract-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!