简体   繁体   中英

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 . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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