反映受保护类的成员

Rag*_*v55 5 c# reflection

using System;
using System.Reflection;

namespace Reflection

{
    class Test
    {
        protected void methodname()
        {
            Console.WriteLine(("in the world of the reflection"));
            Console.Read();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           // BindingFlags eFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public|BindingFlags.NonPublic;
            BindingFlags eFlags = BindingFlags.Instance|BindingFlags.NonPublic;
            Test aTest = new Test();
            MethodInfo mInfoMethod = typeof(Reflection.Test).GetMethod("methodname", eFlags);
            mInfoMethod.Invoke(aTest, null);

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

根据msdn BindingFlags.Nonpublic用于访问非私有成员。如果仅使用此枚举,则Getmethod返回空值。但是,如果使用枚举-实例和非公共,则将调用所需的方法。两者之间有什么区别。当我必须使用实例和公共/非公共组合时。

svi*_*ick 5

根据以下文档GetMethod()

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

Instance/StaticPublic/NonPublic指定两个不同的东西,您必须同时指定两者才能获得结果。