-1

我想使用反射来执行我的函数(名称是GetAverage,没有参数)并且这个函数在Gold的名字中。

我使用此代码:

string MyFunction = "GetAverages";
Type type = typeof(MyGoldClass);
MethodInfo info = type.GetMethod(MyFunction);
int res = (int)info.Invoke(type,null);
res += 3;

但它不起作用,并产生实例错误,我不知道那是什么。注意 MyFunction 是 Gold Class 中的公共函数。我想在其他 C# 页面中调用和执行它。

4

4 回答 4

2

如果你的方法是static试试这个

int res = (int)info.Invoke(null, null);

如果是instance方法试试这个

int res = (int)info.Invoke(instanceOfMyGoldClass, null);

instanceOfMyGoldClass的有效实例在哪里MyGoldClass

参考msdn了解更多信息

如果这无助于发布您的方法定义/签名。我会相应地更新我的答案。

于 2013-09-13T17:50:30.273 回答
1
string MyFunction = "GetAverages";
MethodInfo mi;

mi = typeof(MyGoldClass).GetMethod(MyFunction);
int res = (int)mi.Invoke(new MyGoldClass(), null);
于 2013-09-13T17:50:35.137 回答
0

假设您的方法是公开的:

string MyFunction = "GetAverages";
Type type = typeof(MyGoldClass);
MethodInfo info = type.GetMethod(MyFunction);
int res = (int)info.Invoke(new MyGoldClass(), null);
res += 3;

看看MethodInfo.Invoke

于 2013-09-13T17:53:03.137 回答
0

Invoke 方法有 2 个参数

1st-应该调用该方法的对象

2nd-传递给方法的参数

如果方法是“静态的”,则不能使用对象调用它,因此请使用

int res=(int)info.Invoke(null,null);

如果该方法是非静态的,则应传递 MyGoldClass 的对象来调用该方法,因此请使用

int res=(int)info.Invoke(new MyGoldClass(),null);
于 2013-09-13T17:54:21.937 回答