如何查找C#类的内部属性? 保护? 保护内部?

如果我有一个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 { 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返回内部和私有属性。 BindingFlags上的其他辅助function类型似乎没有标志。

如何获取仅包含内部属性的列表/数组? 在相关的说明中,但对我的应用程序来说不是必需的,那么受保护或受保护的内部呢?

当您使用BindingFlags.NonPublic获取属性信息时,可以分别使用GetGetMethod(true)GetSetMethod(true)找到getter或setter。 然后,您可以检查以下属性(方法信息)以获得准确的访问级别:

  • propertyInfo.GetGetMethod(true).IsPrivate表示私有
  • propertyInfo.GetGetMethod(true).IsFamily表示受保护
  • propertyInfo.GetGetMethod(true).IsAssembly表示内部
  • propertyInfo.GetGetMethod(true).IsFamilyOrAssembly表示受保护的内部

当然, GetSetMethod(true)也是GetSetMethod(true)

请记住,让其中一个访问器(getter或setter)比另一个更受限制是合法的。 如果只有一个访问者,则其可访问性是整个属性的可访问性。 如果两个访问者都在那里,那么容易访问的访问者将为您提供整个属性的可访问性。

使用propertyInfo.CanRead查看是否可以调用propertyInfo.GetGetMethod ,并使用propertyInfo.CanWrite查看是否可以调用propertyInfo.GetSetMethod 。 如果访问者不存在(或者如果它是非公共的并且您要求公共GetGetMethodGetGetMethodGetSetMethod方法将返回null

请参阅MSDN上的这篇文章 。

相关报价:

C#关键字protected和internal在IL中没有任何意义,并且不在reflectionAPI中使用。 IL中的相应术语是Family和Assembly。 要使用reflection标识内部方法,请使用IsAssembly属性。 要标识受保护的内部方法,请使用IsFamilyOrAssembly。

带有System.Reflection.BindingFlags.NonPublic标志的GetProperties返回所有这些: privateinternalprotectedprotected internal