【问题标题】:C# Why are private methods not shown in this reflection example [duplicate]C#为什么在这个反射示例中没有显示私有方法[重复]
【发布时间】:2017-11-07 14:36:09
【问题描述】:

我正在学习 C#,并且正在尝试一个简单的反射示例。我正在尝试从类中获取方法的名称。代码如下:

using System;
using System.Reflection;

namespace Practice
{
    class ReflectionExamples
    {
        private int Sum(int a, int b)
        {
            return a + b;
        }

        public int GetSum(int a, int b)
        {
            int c = Sum(a, b);

            return c;

        }
    }

    class ReflectionDemo
    {
        public static void Execute() // Main calls this
        {
            var a = typeof(ReflectionExamples);

            MethodInfo[] mi = a.GetMethods(); //Using BindingFlags.NonPublic does not show any results
            foreach (MethodInfo m in mi)
            {
                Console.WriteLine(m.Name);
            }
        }
    }
}

这个输出是(缺少总和):

GetNum
ToString
Equals
GetHashCode
GetType

【问题讨论】:

标签: c# reflection


【解决方案1】:

The documentation 状态(向下滚动页面大约一半):

注意

您必须指定 Instance 或 Static 以及 Public 或 NonPublic,否则不会返回任何成员。

Type.GetMethods(BindingFlags)也提到了以下内容:

  • 您必须指定 BindingFlags.InstanceBindingFlags.Static 才能获得回报。

  • 指定 BindingFlags.NonPublic 以在搜索中包含非公共方法(即私有、内部和受保护的方法)。只返回基类上的受保护和内部方法;不返回基类的私有方法。

因此您需要同时指定BindingFlags.NonPublicBindingFlags.Instance

MethodInfo[] mi = a.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2013-03-04
    • 2010-09-26
    • 2015-08-02
    • 1970-01-01
    • 2010-12-21
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多