有没有办法声明以任何 lambda 作为参数的方法?

我正在尝试用 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 或者我应该使用完全不同的方法?


猛跑小猪
浏览 62回答 2
2回答

一只名叫tom的猫

如果你确实需要这种功能,你可以这样做。public delegate object GenericCommand (params object[] parameters);然后,您需要为您想要存储的每个符合 GenericCommand 定义的方法提供重载。下面是一个示例。using System;using System.Collections.Generic;public class Program{&nbsp; &nbsp; public delegate object GenericCommand (params object[] parameters);&nbsp; &nbsp; public static object Function1 (params object[] parameters) => Function1 ((int)parameters[0], (int)parameters[1]);&nbsp; &nbsp; public static int Function1 (int i, int j) => (i + j);&nbsp; &nbsp; private static Dictionary<string, GenericCommand> commands;&nbsp; &nbsp; public static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; commands = new Dictionary<string, GenericCommand> ();&nbsp; &nbsp; &nbsp; &nbsp; commands.Add ("Function1", Function1);&nbsp; &nbsp; &nbsp; &nbsp; int i = (int)commands["Function1"](1, 2);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine (i); // 3&nbsp; &nbsp; }&nbsp; &nbsp;}综上所述,在 C# 这样的语言中执行此操作有点棘手,这是有原因的。在强类型语言中,期望是当调用方法时,用户心中有一组特定的输入,并期望得到特定类型的输出。通常不需要像这样不伦不类的东西,GenericCommand因为如果您知道方法的名称以及它通常所在的位置,为什么不直接调用它呢?如果您发现自己的程序中经常需要这种功能,那么我会考虑用另一种语言编写基线的这一部分。我对此的了解有限,但我相信F#可以轻松完成您所要求的任务。Javascript 是另一种选择,但 F# 是作为 C# 的姊妹函数语言编写的,因此它可能更容易集成到您的项目中。函数式语言(据我所知)更关心您所编写内容的纯粹功能,而不是操作数的性质,尽管我不太确定它对参数的数量是否不可知。这当然值得研究。

HUWWW

除了编译为Expressions 时之外,lambda 都会编译为 的实例System.Delegate。但这是一种非常模糊的类型,您必须使用反射来发现任何东西。Action您可以通过声明一组接受、Action<T>、等的重载来做得更好。Action<T1, T2>这些是返回 的函数的 BCL 内置委托类型void。
打开App,查看更多内容
随时随地看视频慕课网APP