我正在尝试用 C# 编写一个方法来接受任何类型的 lambda,但我不知道该怎么做。
我正在开发一个将处理文本命令的类。我想以这样一种方式实现它,即从处理特定命令的 lambda 表达式自动确定参数。
这是我想要获取的 API 的示例:
commandProcessor.AddCommand("setpos", (int x, int y)=>{
//do stuff
});
commandProcessor.AddCommand("changename",(string newName)=>{
//do completely different stuff
});
我的命令处理器看起来像这样:
Dictionary<string, MagicType> mCommands;
public void AddCommand(string commandName, MagicType commandHandler){
mCommands[commandName] = commandHandler;
}
是否有我可以使用的 MagicType 或者我应该使用完全不同的方法?
如果你真的需要这种功能,你可以这样做。
public delegate object GenericCommand (params object[] parameters);
然后您需要为您想要存储的每个方法提供一个重载,该重载符合 GenericCommand 的定义。
这是一个示例。
using System;
using System.Collections.Generic;
public class Program
{
public delegate object GenericCommand (params object[] parameters);
public static object Function1 (params object[] parameters) => Function1 ((int)parameters[0], (int)parameters[1]);
public static int Function1 (int i, int j) => (i + j);
private static Dictionary<string, GenericCommand> commands;
public static void Main()
{
commands = new Dictionary<string, GenericCommand> ();
commands.Add ("Function1", Function1);
int i = (int)commands["Function1"](1, 2);
Console.WriteLine (i); // 3
}
}
综上所述,用 C# 这样的语言做这件事有点棘手是有原因的。在强类型语言中,预期是在调用方法时,用户心中有一组特定的输入,并期望得到特定类型的输出。通常很少需要像 GenericCommand
这样不起眼的东西,因为如果您知道方法的名称及其通常所在的位置,为什么不直接调用它呢?
如果您发现自己的程序中经常需要这种功能,那么我会考虑用另一种语言编写您的基线部分。我对它的了解有限,但我相信F#可以轻松完成您的要求。 Javascript 是另一种选择,但 F# 是作为 C# 的姐妹函数式语言编写的,因此它可能更容易集成到您的项目中。函数式语言(据我所知)比操作数的性质更关心你所写内容的纯功能性,尽管我不太确定它对参数的数量是不可知的。这当然值得研究。