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.
Using reflection in C# language, we can access the private fields, data and functions etc.
Yes, the protected method of a superclass can be overridden by a subclass.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With