簡體   English   中英

反思:私有屬性如何提取自定義屬性

[英]reflection: private property how to extract custom attribute

嗨,有可能在私有財產中檢索自定義屬性

   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;

        }
    }

謝謝

是的,這完全有可能。 您擁有的代碼(雖然有點麻煩,因為您在使用自己的類型進行工作,因為您不需要反射),所以非常接近:

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM