how to invoke a function using refelection
hi how to invoke this function using the reflection
for eg:
void开发者_开发知识库 testFunction(int a , int b , out b)
void testFunction(int a, int b, ref b)
Is this what you're after?
using System;
using System.Reflection;
class Test
{
public void testFunction1(int a, int b, ref int c)
{
c += a + b;
}
public void testFunction2(int a, int b, out int c)
{
c = a + b;
}
static void Main()
{
MethodInfo method = typeof(Test).GetMethod("testFunction1");
object[] args = new object[] { 1, 2, 3 };
Test instance = new Test();
method.Invoke(instance, args);
// The ref parameter will be updated in the array, so this prints 6
Console.WriteLine(args[2]);
method = typeof(Test).GetMethod("testFunction2");
// The third argument here has to be of the right type,
// but the method itself will ignore it
args = new object[] { 1, 2, 999 };
method.Invoke(instance, args);
// The ref parameter will be updated in the array, so this prints 3
Console.WriteLine(args[2]);
}
}
Note that you have to keep a reference to the array used to specify the arguments, if you want to get at the updated ref/out parameter values afterwards.
If you need non-public methods, you need to specify BindingFlags
in the call to GetMethod
.
First, that function needs to be a member of a class:
class MyClass
{
public: void testFunction(int a , int b , out b);
}
Then, you need an instance of the class:
MyClass myObj = new MyClass();
Then, use reflection to get the function:
MethodInfo[] myMethods = typeof(myObj).GetMethods(BindingFlags.Public);
Iterate through the methods to find the one you want:
MethodInfo myTarget = NULL;
foreach(MethodInfo mi in myMethods)
{
if (mi.Name == "testFunction")
{
myTarget = mi;
break;
}
}
Finally, invoke it:
int[] myParams = {1, 2, 3};
myTarget.Invoke(myObj, (object[])myParams);
精彩评论