反思:私有属性如何提取自定义属性 [英] reflection: private property how to extract custom attribute
本文介绍了反思:私有属性如何提取自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有可能在私有财产中检索自定义属性
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;
}
}
谢谢
推荐答案
是的,这完全有可能。您拥有的代码(虽然有点麻烦,因为您使用自己的类型,因为您不需要反射),所以非常接近:
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
}
}
这篇关于反思:私有属性如何提取自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文