本文介绍了如何查找 C# 类的内部属性?保护?受保护的内部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 C# 类 MyClass 如下:

If I have a C# class MyClass as below:

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 返回 Internal 和 Private 属性.BindingFlags.

The code above compiles are runs without any assertion failures. NonPublic returns the Internal and Private properties. There does not appear to be flags for the other accessibility types on BindingFlags.

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

How do I get a list/array of only the properties that are internal? On a related note, but not necessary for my application, what about protected, or protected internal?

推荐答案

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

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:

当然对于 GetSetMethod(true) 也是如此.

and similarly for GetSetMethod(true) of course.

请记住,让一个访问器(getter 或 setter)比另一个更受限制是合法的.如果只有一个访问器,它的可访问性就是整个属性的可访问性.如果两个访问器都存在,可访问的一个给你整个属性的可访问性.

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.

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

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).

这篇关于如何查找 C# 类的内部属性?保护?受保护的内部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!