How do I look up the internal properties of a C# class? protected? protected internal?

泄露秘密 提交于 2019-11-30 12:42:01

When you get the property infos with BindingFlags.NonPublic, you find the getter or setter by using GetGetMethod(true) and GetSetMethod(true), respectively. You can then check the following properties (of the method info) to get the exact access level:

  • propertyInfo.GetGetMethod(true).IsPrivate means private
  • propertyInfo.GetGetMethod(true).IsFamily means protected
  • propertyInfo.GetGetMethod(true).IsAssembly means internal
  • propertyInfo.GetGetMethod(true).IsFamilyOrAssembly means protected internal

and similarly for GetSetMethod(true) of course.

Remember that it is legal to have one of the accessors (getter or setter) more restricted than the other one. If there is just one accessor, its accessibility is the accessibility of the entire property. If both accessors are there, the most accessible one gives you the accessibility of the whole property.

Use propertyInfo.CanRead to see if it's OK to call propertyInfo.GetGetMethod, and use propertyInfo.CanWrite to see if it's OK to call propertyInfo.GetSetMethod. The GetGetMethod and GetSetMethod methods return null if the accessor does not exist (or if it is non-public and you asked for a public one).

See this article on MSDN.

Relevant quote:

The C# keywords protected and internal have no meaning in IL and are not used in the reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.

GetProperties with System.Reflection.BindingFlags.NonPublic flag returns all of them: private, internal, protected and protected internal.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!