Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW TO get an overloaded private/protected method using reflection

Tags:

c#

reflection

using System;
using System.Reflection;

namespace Reflection        
{
    class Test
    {
        protected void methodname(int i)
        {
            Console.WriteLine(("in the world of the reflection- only i"));
            Console.Read();
        }    
        protected void methodname(int i, int j)
        {
            Console.WriteLine(("in the world of the reflection  i , j"));
            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, new object[] { 10 ,20});   
        }
    }
}

I want to call both Getmethod() overloaded methods. If i give the method name , an runtime error is thrown(ambigous method call) . How to avoid this and how each method can be called.

like image 727
Raghav55 Avatar asked Dec 07 '11 10:12

Raghav55


People also ask

Can we access private methods using reflection C#?

Using reflection in C# language, we can access the private fields, data and functions etc.

Can we override protected method in C#?

Yes, the protected method of a superclass can be overridden by a subclass.


1 Answers

You have to pass types of your overloaded method, this is how reflection sorts out your desired method when there's a overload.

You can't call both the methods as it has different types of input parameter. You have to know exactly which one you exactly want to call, and pass along a Type[], for instance:

// invoking overload with two parameters
MethodInfo mInfoMethod =
    typeof(Reflection.Test).GetMethod(
        "methodname",
        BindingFlags.Instance | BindingFlags.NonPublic,
        Type.DefaultBinder,
        new[] {typeof (int), typeof (int)},
        null);

mInfoMethod.Invoke(aTest, new object[] { 10 ,20});

OR

// invoking overload with one parameters
MethodInfo mInfoMethod =
    typeof(Reflection.Test).GetMethod(
        "methodname",
        vBindingFlags.Instance | BindingFlags.NonPublic,
        Type.DefaultBinder,
        new[] { typeof (int) },
        null);

mInfoMethod.Invoke(aTest, new object[] { 10 });
like image 71
Abdul Munim Avatar answered Oct 05 '22 00:10

Abdul Munim