c# 中关于MethodBase Invoke方法!

来源:百度知道 编辑:UC知道 时间:2024/09/28 14:50:44
MSDN上的解释我不太理解,能给我个简单的例子么?
并且注明下,谢谢啦!
例如这个MSDN上的例子
using System;
using System.Reflection;
using System.Windows.Forms;

public class A
{
public virtual int method() { return 0; }
}

public class B
{
public virtual int method() { return 1; }
}

class Mymethodinfo
{
public static int Main()
{
Console.WriteLine("\nReflection.MethodInfo");
A MyA = new A();
B MyB = new B();

// Get the Type and MethodInfo.
Type MyTypea = Type.GetType("A");
MethodInfo Mymethodinfoa = MyTypea.GetMethod("method");

Type MyTypeb = Type.GetType("B");
MethodInfo Mymethodinfob = MyTypeb.GetMethod("method");

// Get and display the Invoke method.
Console.Write("\nFirst method - "

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.Reflection;

namespace Demo
{
public class TestClass
{
public void Test1( string msg