您可以将一个方法传递到另一个采用 Func<> 的方法中。但是,您能否将其作为动态命名的字符串传入,以便可以动态传入什么方法?
值得将"传递值">一个方法传递到另一个需要
Func<>
的方法中。
与"首先创建值"分开。当您编写如下代码时:
InvokeSomeDelegate(MethodToInvoke);
这是执行方法组转换以创建委托实例。换句话说,它相当于:
Func<Whatever> func = MethodToInvoke;
InvokeSomeDelegate(func);
因此,实际上问题不在于如何将字符串传递到方法中,而在于如何基于字符串创建委托。这反过来又导致了什么样的方法,它是什么类型的问题等等。
您要使用的框架方法是Delegate.CreateDelegate
,但具体如何使用它将取决于上下文,以便您可以找到正确的反射MethodInfo
。下面是一个示例:
using System;
using System.Reflection;
class Test
{
static void Main()
{
InvokeFunc("Double");
InvokeFunc("Quadruple");
InvokeFunc("AddOne");
}
static void InvokeFunc(string name)
{
// Note that in our case they're all private static methods. You'd
// need to adjust the binding flags if that's not the case. If you
// need to worry about multiple overloads, that makes it harder too.
MethodInfo method = typeof(Test)
.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static);
// TODO: Validate that you've got a method
var func = (Func<int, int>) Delegate.CreateDelegate(
typeof(Func<int, int>), // Delegate type to create
null, // Target of method call; null because ours are static
method); // Method to create a delegate for
var result = func(10);
Console.WriteLine($"{name}(10) => {result}");
}
static int Double(int x) => x * 2;
static int Quadruple(int x) => x * 4;
static int AddOne(int x) => x + 1;
}
请注意,查找方法然后创建委托的所有反射都相对较慢。如果在执行此操作时存在任何明显的性能限制,则可能需要添加缓存。