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

如何通过反射将静态方法分配给C#中的委托,c#,reflection,C#,Reflection,考虑以下代码: internal delegate object FactoryMethod(); String myStaticMethod = "FooFactory.GetInstance()"; 现在假设我有以下代码: internal delegate object FactoryMethod(); String myStaticMethod = "FooFactory.GetInstance()"; 我该如何做以下工作 FactoryMethod myMethod = //A

考虑以下代码:

internal delegate object FactoryMethod();
String myStaticMethod = "FooFactory.GetInstance()";
现在假设我有以下代码:

internal delegate object FactoryMethod();
String myStaticMethod = "FooFactory.GetInstance()";
我该如何做以下工作

FactoryMethod myMethod = //A delegate pointing to FooFactory.GetInstance()
我在谷歌上搜索,但似乎找不到一个干净的例子,或者至少找不到一个处理静态方法的例子。

我发现:

typeof(YourClass).GetMethod("GetInstance", BindingFlags.Public | BindingFlags.Static);
我发现:

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

使用的重载之一。以下是一种可能的方法:

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

使用的重载之一。以下是一种可能的方法:

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

你真的需要反射吗?我没有考虑任何事情,但我通常在编写超出规范的代码时称之为反射,例如通过字符串创建类的实例。你真的需要反射吗?我没有考虑任何事情,但当我在编写超出规范的代码时,比如通过字符串创建类的实例时,我通常称之为反射。