反射:私有属性如何提取自定义属性
您好,可以在私有财产中检索自定义属性,
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;
}
}
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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: