使用反射調用方法:
一旦知道一個類型所支援的方法,就可以對方法進行調用。調用時,需使用包含在
MethodInfo中的Invoke()方法。調用形式:
object Invoke(object ob, object[] args)
這裡ob是一個對象引用,将調用它所指向的對象上的方法。對于靜态方法,ob必須為null。
所有需要傳遞給方法的參數都必須在args數組中指定。如果方法不需要參數,則args必須為null。
另外,數組args的元素數量參數必須等于參數的數量。Invoke()方法傳回被調用方法的傳回值。
要調用某個方法,隻需在一個MethodInfo執行個體上調用Invoke(),該執行個體通過調用
GetMethods()
方法獲得。請看事例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Reflection
{
class Program
{
static void Main(string[] args)
{
// Demo1();
InvokeMethDemo();
Console.ReadKey();
}
static void InvokeMethDemo()
//獲得MyClass的類型隊形
Type t = typeof(MyClass);
MyClass reflectOb = new MyClass(10, 20);
Console.WriteLine("類名:{0}", t.Name);
Console.WriteLine("本類所提供的方法有:");
MethodInfo[] mi = t.GetMethods();
int val;
foreach (MethodInfo m in mi)
{
Console.WriteLine();
//顯示參數
ParameterInfo[] pi = m.GetParameters();
if (m.Name == "Set" && pi[0].ParameterType == typeof(int))
{
Console.Write("Set(int,int) ");
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if (m.Name == "Set" && pi[0].ParameterType == typeof(double))
Console.Write("Set(double,double) ");
args[0] = 2.34;
args[1] = 13.56;
else if (m.Name.CompareTo("Sum") == 0) {
Console.Write("Sum() ");
val = (int)m.Invoke(reflectOb, null);
Console.WriteLine("Sum is {0}",val);
else if(m.Name.CompareTo("IsBetween")==0)
object[] args = new object[1];
args[0] = 17;
if ((bool)m.Invoke(reflectOb, args))
{
Console.WriteLine("{0}在x和y之間",args[0]);
}
}
}
}
class MyClass
int x;
int y;
public MyClass(int i, int j)
x = i;
y = j;
public int Sum()
return x + y;
public bool IsBetween(int i)
if (x < i && i < y)
return true;
else
return false;
public void Set(int a, int b)
x = a;
y = b;
Show();
public void Set(double a, double b)
x = (int)a;
y = (int)b;
public void Show()
Console.WriteLine("x:{0},y:{1}", x, y);
運作結果如下:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcugzNmdDO1EGN4UWN3gjN1kzNmRzMhVDNlJzMmVmZxcTYfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)