Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection of protected member of a class

Tags:

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

        }
    }
}

As per the msdn BindingFlags.Nonpublic is used to access the non private members. If I use only this enum the Getmethod returns null value. 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.

like image 244
Raghav55 Avatar asked Dec 07 '11 09:12

Raghav55


2 Answers

Per the documentation of GetMethod():

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

Instance/Static and Public/NonPublic specify two different things and you have to specify both in order to get the result.

like image 124
svick Avatar answered Oct 15 '22 02:10

svick


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)

like image 39
C.Evenhuis Avatar answered Oct 15 '22 04:10

C.Evenhuis