问题
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