The following code executes without error and prints “In some“, which means that the statement
m[0].Invoke(o, args);
invokes the function some which is a member of the foo class, on object o and affects its public variable i. But when we uncomment the last line of the code and try to compile it, it produces an error. Why??
using System;
using System.Reflection;
class foo
{
public int i;
public foo(int ii = 0)
{
i = ii;
}
public void some(int ii)
{
i = ii;
Console.WriteLine("In some ");
}
}
class main
{
static public void Main()
{
foo f = new foo();
object o = new foo();
Type t = typeof(foo);
object[] args = new object[1];
args[0] = 9;
MethodInfo[] m = t.GetMethods();
m[0].Invoke(o, args);
//Console.WriteLine(o.i);
}
}
Because you’ve declared
oasSystem.Object, which doesn’t have a variableidefined on it as far as the compiler is concerned. You’d need to either cast it to the known type, or use reflection to retrieve this value.For example:
Alternatively, use reflection to get the value: