C# 反射:私有属性如何提取自定义属性

C# 反射:私有属性如何提取自定义属性,c#,custom-attributes,C#,Custom Attributes,嗨,可以在私有属性中检索自定义属性 public class TestAttr { [SaveInState] protected string testPrivate { get { return "test private"; } } [SaveInState] public string testPublic { get{ return "test public"; }} public IDi

嗨,可以在私有属性中检索自定义属性

   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;

        }
    }
公共类测试
{
[SaveInState]
受保护字符串testPrivate{get{返回“testPrivate”;}
[SaveInState]
公共字符串testPublic{get{返回“testPublic”;}
公共IDictionary dumpVars()
{
IDictionary dict=新字典();
Type ownerClassType=this.GetType();
foreach(ownerClassType.GetProperties(BindingFlags.NonPublic)中的var mi)
{
var varAttrib=Attribute.GetCustomAttribute(mi,typeof(SaveInStateAttribute));
if(varAttrib!=null)
{
dict.Add(mi.Name,mi.GetValue(this,null));
}
}
返回命令;
}
}

谢谢

是的,这是完全可能的。您拥有的代码(虽然有点毫无意义,因为您使用的是自己的类型,所以不需要反射)非常接近:

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

是的,这是完全可能的。您拥有的代码(虽然有点毫无意义,因为您使用的是自己的类型,所以不需要反射)非常接近:

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

伟大的感谢它的工作…,是的,你是对的,但课堂上不需要反思,只是一个例子,谢谢!谢谢它的工作…,是的,你是对的,但课堂内不需要反思,只是一个例子,谢谢