C# 如何在 .NET 中动态调用类的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1120228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically call a class' method in .NET?
提问by pistacchio
How to pass a class and a method name as stringsand invoke that class' method?
如何将类和方法名称作为字符串传递并调用该类的方法?
Like
喜欢
void caller(string myclass, string mymethod){
// call myclass.mymethod();
}
Thanks
谢谢
采纳答案by Andrew Hare
You will want to use reflection.
您将需要使用反射。
Here is a simple example:
这是一个简单的例子:
using System;
using System.Reflection;
class Program
{
static void Main()
{
caller("Foo", "Bar");
}
static void caller(String myclass, String mymethod)
{
// Get a type from the string
Type type = Type.GetType(myclass);
// Create an instance of that type
Object obj = Activator.CreateInstance(type);
// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod(mymethod);
// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);
}
}
class Foo
{
public void Bar()
{
Console.WriteLine("Bar");
}
}
Now this is a verysimple example, devoid of error checking and also ignores bigger problems like what to do if the type lives in another assembly but I think this should set you on the right track.
现在这是一个非常简单的例子,没有错误检查,也忽略了更大的问题,比如如果类型存在于另一个程序集中该怎么办,但我认为这应该让你走上正确的轨道。
回答by Kenan E. K.
Something like this:
像这样的东西:
public object InvokeByName(string typeName, string methodName)
{
Type callType = Type.GetType(typeName);
return callType.InvokeMember(methodName,
BindingFlags.InvokeMethod | BindingFlags.Public,
null, null, null);
}
You should modify the binding flags according to the method you wish to call, as well as check the Type.InvokeMember method in msdn to be certain of what you really need.
您应该根据您希望调用的方法修改绑定标志,并检查 msdn 中的 Type.InvokeMember 方法以确定您真正需要什么。
回答by clemahieu
What's your reason for doing this? More than likely you can do this without reflection, up to and including dynamic assembly loading.
你这样做的原因是什么?您很可能无需反射就可以做到这一点,直到并包括动态程序集加载。