-1

I Want to use Reflection to execute my function(Which name is GetAverage,With no parameter) And this function is in class by name of Gold.

I Use This Code :

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

But it do not work and Make instance Error Which i do not know what that is. ATTENTION MyFunction Is a Public Function In Gold Class.And i Want Calling and executing This in Other C# Page.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
Amin AmiriDarban
  • 2,031
  • 4
  • 24
  • 32

4 Answers4

2

If your method is static try this

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

If it is instance method try this

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

where instanceOfMyGoldClass is a valid instancce of MyGoldClass

Refer msdn for more info

If this doesn't help post your method definition/signature. I'll update my answer accordingly.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1
string MyFunction = "GetAverages";
MethodInfo mi;

mi = typeof(MyGoldClass).GetMethod(MyFunction);
int res = (int)mi.Invoke(new MyGoldClass(), null);
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
0

Assuming your method is public:

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

Take a look at MethodInfo.Invoke

Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
0

the Invoke method takes 2 parameters

1st-the object on which the method should be invoked

2nd-the arguments passed to the method

if the method is "static", it can not be called using an object so use

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

if the method is non-static, an object of MyGoldClass should be passed to invoke the method so use

int res=(int)info.Invoke(new MyGoldClass(),null);
Nithin Nayagam
  • 458
  • 2
  • 5
  • 9