简体   繁体   English

反映受保护的成员

[英]Reflection of protected member of a class

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

        }
    }
}

As per the msdn BindingFlags.Nonpublic is used to access the non private members. 根据msdn BindingFlags.Nonpublic用于访问非私有成员。 If I use only this enum the Getmethod returns null value. 如果我只使用此枚举,Getmethod将返回null值。 But if use the enum - Instance and nonpublic the required method is called. 但是如果使用枚举 - 实例和非公共,则调用所需的方法。 What is the difference between these two. 这两者有什么区别。 When I have to use instance and public/nonpublic combination. 当我必须使用实例和公共/非公共组合。

Per the documentation of GetMethod() : 根据GetMethod()的文档

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. 您必须指定BindingFlags.InstanceBindingFlags.Static才能获得返回。

Instance / Static and Public / NonPublic specify two different things and you have to specify both in order to get the result. Instance / StaticPublic / NonPublic指定两个不同的东西,你必须指定两个以获得结果。

If you don't specify the enum, the default is used. 如果未指定枚举,则使用默认值。 If you do, you have to specify both: 如果这样做,您必须同时指定:

  • Public or NonPublic (or both) 公共或非公共(或两者)
  • Static or Instance (or both) 静态或实例(或两者)

(See the note in the remarks section on http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx ) (请参阅http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx上备注部分中的注释)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM