简体   繁体   English

如何通过反射将静态方法分配给C#中的委托

[英]How do I assign a static method to a delegate in C# via reflection

Consider the following code: 考虑以下代码:

internal delegate object FactoryMethod();

Now say I have the following code: 现在说我有以下代码:

String myStaticMethod = "FooFactory.GetInstance()";

How do I do the following? 我该怎么办?

FactoryMethod myMethod = //A delegate pointing to FooFactory.GetInstance()

I'm googling away, but I can't seem to find a clean example or at least one that deals with static methods. 我正在搜寻,但是似乎找不到一个干净的示例,或者至少找不到一个处理静态方法的示例。

Use one of overloads of the Delegate.CreateDelegate . 使用Delegate.CreateDelegate的重载之一。 Here is one possible way: 这是一种可能的方法:

var className = "FooFactory";
var methodName = "GetInstance";
var implType = Type.GetType(className);
var implMethod = implType.GetMethod(methodName, new Type[0]);
var res = Delegate.CreateDelegate(typeof(FactoryMethod), implMethod);

我发现了这一点:

typeof(YourClass).GetMethod("GetInstance", BindingFlags.Public | BindingFlags.Static);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM