C# 将可能有参数或没有参数的函数存储到变量。行动<;T>;具有未知数量和类型的变量

C# 将可能有参数或没有参数的函数存储到变量。行动<;T>;具有未知数量和类型的变量,c#,delegates,console-application,C#,Delegates,Console Application,我正在为控制台应用程序开发一个命令解析器类,但我在将命令函数存储到变量时遇到了麻烦。我想将一个可能有参数或没有参数的函数存储到Command对象中的commandFunc变量 这些代码适用于没有参数的函数。如何获得对此的参数支持?例如:像output(string msg){..}这样的函数 在CommandParser.Loop中,它在List中搜索输入的命令,然后从中运行Execute方法 public class Command { public string commandTex

我正在为控制台应用程序开发一个命令解析器类,但我在将命令函数存储到变量时遇到了麻烦。我想将一个可能有参数或没有参数的函数存储到Command对象中的commandFunc变量

这些代码适用于没有参数的函数。如何获得对此的参数支持?例如:像output(string msg){..}这样的函数

在CommandParser.Loop中,它在List中搜索输入的命令,然后从中运行Execute方法

public class Command
{
    public string commandText { get; set; }
    public Action commandFunc { get; set; }

    public void Execute()
    {
        this.commandFunc();
    }
}
例如,execute方法可以是这样的:

public void Execute(Parameters params)
{
    this.commandFunc(params);
}
PS:CommandParser.Loop()


基本上你需要做的是扩展对象层次结构

在C#中,泛型不允许
某些东西
,因此您需要做的是:

public interface ICommand
{
    void Execute();
}
这是添加了接口的当前实现

public class Command : ICommand
{
    public string commandText { get; set; }
    public Action commandFunc { get; set; }

    public void Execute()
    {
        this.commandFunc();
    }
}
并且是具有参数的委托的通用实现

public class Command<T> : ICommand
{
    public string       commandText  { get; set; }
    public Action<T>    commandFunc  { get; set; }
    public T            commandParam { get; set; }

    public void Execute()
    {
        this.commandFunc(commandParam);
    }
}
公共类命令:ICommand
{
公共字符串commandText{get;set;}
公共操作命令func{get;set;}
公共T命令参数{get;set;}
public void Execute()
{
this.commandFunc(commandParam);
}
}
如果需要实现更多参数,可以复制原始参数或使用
Tuple
类作为通用参数(例如
Tuple

正如Jon Skeet在评论中提到的:

另一件事是,您可能需要解析这些通用命令中的参数(由
commandParam
表示)。您应该使用参数(如委托)初始化这些命令以分析参数。在命令之外这样做将是一个混乱,并打破了整个通用性/接口概念。但它可能在较小的范围内工作。

您希望它如何从字符串数组转换为正确的参数类型?我写它是为了更好地回答我的问题。这只是一个例子,但它触及了问题中一个无法解释的部分的核心:如果要使用不同数量的参数执行不同的命令,您希望如何执行它们?数据从何而来?在CommandParser.Loop()中,它通过Console.ReadLine()获取输入,并将其按空格分割。返回数组的第一个元素是commandText,其他元素是parameters。在问题中添加了循环函数。检查一下,你的循环没有显示它向命令传递任何信息。。。(也不清楚您希望
cmdInput!=new Command()
作为一个条件实现什么…我怀疑您希望
cmdInput!=null
)也许您可以使用
操作
让命令解析其输入?
public class Command : ICommand
{
    public string commandText { get; set; }
    public Action commandFunc { get; set; }

    public void Execute()
    {
        this.commandFunc();
    }
}
public class Command<T> : ICommand
{
    public string       commandText  { get; set; }
    public Action<T>    commandFunc  { get; set; }
    public T            commandParam { get; set; }

    public void Execute()
    {
        this.commandFunc(commandParam);
    }
}