MethodBase Invoke方法
MethodBase 的 Invoke 方法是一个抽象方法。
当在派生类中重写时,调用具有给定参数的反射的方法或构造函数。
MethodBase 是 MethodInfo 和 ConstructorInfo 的基类。
Invoke方法,有两个重载,功能就是调用指定的函数。
举个简单的例子,使用第一个重载,它的参数比较简单,只有两个参数。
public Object Invoke(
Object obj,
Object[] parameters
)
第一个参数:对其调用方法或构造函数的对象。如果方法是静态的,则忽略此参数。如果构造函数是静态的,则此参数必须为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing) 或定义该构造函数的类的实例。
第二个参数:调用的方法或构造函数的参数列表。这是一个对象数组,这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。如果没有任何参数,则 parameters 应为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。
如果此实例所表示的方法或构造函数采用 ref 参数(在 Visual Basic 中为 ByRef),使用此函数调用该方法或构造函数时,该参数不需要任何特殊属性。如果数组中的对象未用值来显式初始化,则该对象将包含该对象类型的默认值。对于引用类型的元素,该值为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。对于值类型的元素,该值为 0、0.0 或 false,具体取决于特定的元素类型。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Type testClassType = Type.GetType("ConsoleApplication1.TestClass, ConsoleApplication1", false);
if (testClassType != null)
{
object instance = Activator.CreateInstance(testClassType, 10, 20);
MethodInfo test1 = testClassType.GetMethod("Test1", BindingFlags.Instance | BindingFlags.Public);
test1.Invoke(instance, new object[] { "hello word!" });
MethodInfo test2 = testClassType.GetMethod("Test2", BindingFlags.Instance | BindingFlags.Public);
int result = (int)test2.Invoke(instance, new object[] { 1, "good", 'x' });
Console.WriteLine("result = {0}", result);
MethodInfo test3 = testClassType.GetMethod("Test3", BindingFlags.Static | BindingFlags.Public);
string result1 = (string)test3.Invoke(null, new object[] { "test3" });
Console.WriteLine("result1 = {0}", result1);
Console.ReadKey();
}
}
}
public class TestClass
{
public void Test1(string msg)
{
Console.WriteLine("TestClass.Test1 Invoked with parameter( msg: {0} )", msg);
}
public int Test2(int a, string b, char c)
{
Console.WriteLine("TestClass.Test2 Invoked with parameter( a: {0}, b: {1}, c: {2} )", a, b, c);
return a;
}
public static string Test3(string s)
{
Console.WriteLine("TestClass.Test3 Invoked with parameter( s: {0} )", s);
return DateTime.Now.ToString();
}
public TestClass(int a, int b)
{
Console.WriteLine("TestClass created with parameter( a: {0}, b: {1} )", a, b);
}
}
}

浙公网安备 33010602011771号