2011-03-25 129 views
0

喜有可能在私有财产来获取自定义属性反思:私有财产如何提取自定义属性

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; 

     } 
    } 

感谢

回答

4

是的,这是完全可能的。你有的代码(虽然你没有必要反思,因为你在你自己的类型工作,有点毫无意义)是非常接近:

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

太棒了!谢谢它的作品...,是的,你是对的,但内部课堂是不需要反思,但只是一个例子谢谢 – LXG 2011-03-27 18:11:45