使用反射检测属性上的访问修饰符类型 [英] Detect access modifier type on a property using Reflection
问题描述
我已经编写了一些代码来使用反射来查看属性。我已经使用反射从类中检索了属性列表。
I have written some code to look at properties using reflection. I have retrieved a list of properties from the class using reflection.
但是我需要找出该属性是公共属性还是受保护的属性。例如:
However I need to find out if the property is public or protected. eg:
public string Name{get;set;}
protected int Age{get;set;}
PropertyInfo类似乎没有公开有关该属性的信息。还有另一种方法吗?
The PropertyInfo class does not seem to expose this information about the property. Is there another way to do this?
推荐答案
因为属性只是一对 get上的语法糖
/ set
方法,不存在属性反射方式的可访问性。相反,您必须分别找出 get
和 set
方法的可访问性级别。为此,请使用 GetGetMethod
和 GetSetMethod
方法,并且有各种 IsPrivate
, IsPublic
和其他方法和属性。
Since properties are just syntactic sugar over a pair of get
/set
methods, there's no such thing as "accessibility" of a property reflection-wise. Rather, you'll have to find out accessibility levels of get
and set
methods separately. To that end, retrieve appropriate MethodInfo
objects with GetGetMethod
and GetSetMethod
methods, and from there are various IsPrivate
, IsPublic
and other methods and properties.
这篇关于使用反射检测属性上的访问修饰符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!