如何查找C#类的内部属性?受保护的?内部保护?
如果我有一个C类如何查找C#类的内部属性?受保护的?内部保护?,c#,system.reflection,C#,System.reflection,如果我有一个C类MyClass,如下所示: using System.Diagnostics; namespace ConsoleApplication1 { class MyClass { public int pPublic {get;set;} private int pPrivate {get;set;} internal int pInternal {get;set;} } class Program
MyClass
,如下所示:
using System.Diagnostics;
namespace ConsoleApplication1
{
class MyClass
{
public int pPublic {get;set;}
private int pPrivate {get;set;}
internal int pInternal {get;set;}
}
class Program
{
static void Main(string[] args)
{
Debug.Assert(typeof(MyClass).GetProperties(
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance).Length == 1);
Debug.Assert(typeof(MyClass).GetProperties(
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance).Length == 2);
// internal?
// protected?
// protected internal?
}
}
}
以上编译的代码运行时没有任何断言失败。NonPublic返回内部和私有属性。上的其他辅助功能类型似乎没有标志
如何仅获取内部属性的列表/数组?请注意,对于我的应用程序来说不是必需的,那么受保护的或受保护的内部属性呢?
GetProperties
与System.Reflection.BindingFlags.NonPublic
标志返回所有这些属性:private
、internal
、受保护的
和受保护的内部
请参见MSDN上的
相关报价:
C#关键字protected和internal在IL中没有意义,是
反射API中未使用。IL中的相应术语为
家庭和集会。要使用反射识别内部方法,
使用IsAssembly属性。要识别受保护的内部方法,
使用iFamilyOrder程序集
当您使用
bindingsflags.NonPublic
获取属性信息时,您可以分别使用GetGetMethod(true)
和GetSetMethod(true)
查找getter或setter。然后,您可以检查(方法信息)的以下属性以获得确切的访问级别:
表示私有propertyInfo.GetMethod(true).IsPrivate
表示受保护propertyInfo.getMethod(true).IsFamily
表示内部propertyInfo.getMethod(true).IsAssembly
表示受保护的内部propertyInfo.getMethod(true).IsFamilyOrAssembly
表示私有保护propertyInfo.getMethod(true).IsFamilyAndAssembly
GetSetMethod(true)
也是如此
请记住,让一个访问器(getter或setter)比另一个访问器受到更多限制是合法的。如果只有一个访问器,则其可访问性是整个属性的可访问性。如果两个访问器都存在,那么最容易访问的访问器将为您提供整个属性的访问权限
使用
propertyInfo.CanRead
查看是否可以调用propertyInfo.GetGetMethod
,使用propertyInfo.CanWrite
查看调用propertyInfo.GetSetMethod
是否可以。如果访问器不存在(或者如果它是非公共的,并且您要求一个公共的),则GetGetMethod
和GetSetMethod
方法返回null
。我认为您不能得到比这更精确的结果。很抱歉不清楚。我在我的问题中添加了“仅”一词,以表明我只想得到这些。你不能得到比public
或nonpublic
更细粒度的数据。这只是关于方法或属性?我不相信有任何区别。我认为有,因为IsAssembly
和IsFamilyAndAssembly
都是在MethodBase
类上声明的,所以它们在PropertyInfo
@MarcinJuraszek上不可用,我想应该在PropertyInfo.getmethod()和PropertyInfo.GetSetMethod()上
提供表示底层方法的MethodInfo
对象。此外,您可能需要在传递true
布尔值的地方点击重载,否则如果属性访问器是非公共的,它将返回null
。另一个选项是调用propertyInfo.GetMethod(true)。i、 e.propertyInfo.getMethod(true).IsPrivate。还要注意的是,我必须像这样调用GetProperties以使其工作于GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);GetProperties(BindingFlags.NonPublic)本身没有work@cgotberg是的,我编辑了我的答案以使用true
参数。否则,它不会给您非公共访问器。谢谢