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});
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想调用两个Getmethod()重载方法.如果我给出方法名称,则抛出运行时错误(ambigous方法调用).如何避免这种情况以及如何调用每种方法.
Abd*_*nim 22
您必须传递重载方法的类型,这是反射在出现过载时对您所需方法进行排序的方式.
您不能同时调用这两个方法,因为它具有不同类型的输入参数.您必须确切地知道您确切要调用哪一个,并传递一个Type[],例如:
// 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});
Run Code Online (Sandbox Code Playgroud)
要么
// 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 });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14487 次 |
| 最近记录: |