如何在运行时动态调用公共函数
本文关键字:函数 调用 动态 运行时 | 更新日期: 2023-09-27 18:21:06
我想像一样在运行时通过函数的名称调用函数
string srFunctionName="MyFunction";
因此,通过使用这个变量,我想调用名为"MyFunction"的函数。我该怎么做?
您可以使用反射:
string strFunctionName = "MyFunction";
// get the type containing the method
Type t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");
// you will need an instance of the type if the method you are
// trying to invoke is not static. If it is static you could leave that null
object instance = Activator.CreateInstance(t);
// the arguments that your method expects
new object[] arguments = new object[] { 1, "foo", false };
// invoke the method
object result = t.InvokeMember(
strFunctionName,
BindingFlags.InvokeMethod,
null,
instance,
arguments
);
更新:
正如评论部分所要求的,这里有一个完整的具有实际功能的示例:
using System;
using System.Reflection;
namespace Foo.Bar
{
public class SomeTypeContainingYourFunction
{
public string MyFunction(int foo, string bar, bool baz)
{
return string.Format("foo: {0}, bar: {1}, baz: {2}", foo, bar, baz);
}
}
}
namespace Bazinga
{
class Program
{
static void Main()
{
var strFunctionName = "MyFunction";
var t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");
var instance = Activator.CreateInstance(t);
var arguments = new object[] { 1, "foo", false };
var result = t.InvokeMember(
strFunctionName,
BindingFlags.InvokeMethod,
null,
instance,
arguments
);
Console.WriteLine(result);
}
}
}
以下是关闭form
的示例
object instance = form;
Type myType = form.GetType();
myType.InvokeMember("Close", BindingFlags.InvokeMethod, null, instance, null);
您可以使用反射创建类的对象,然后使用该对象调用函数。
object Instance = Activator.CreateInstance(t); // t is type
MethodInfo mi = t.GetMethod(srFunctionName);
if (mi != null)
mi.Invoke(Instance, args);
else
logError();