简体   繁体   English

根据字典内容调用函数 C#

[英]Calling Functions Based on Content of a Dictionary C#

I'm working on a program that will have a dictionary storing commands.我正在开发一个程序,该程序将有一个存储命令的字典。 There are two dictionaries, one of executables and one of internal functions.有两个字典,一个是可执行文件,一个是内部函数。 Right now, I'm just using the executable one, which has a command name attached to the path of the executable.现在,我只是使用可执行文件,它有一个附加到可执行文件路径的命令名。 It will check for the input in the dictionary and run the attached exe if possible and run that command.它将检查字典中的输入并在可能的情况下运行附加的 exe 并运行该命令。 I started the function dictionary because there are some functions that are not executables.我启动了 function 字典,因为有些函数不是可执行的。 Would it be possible to do the same thing I did with the executables with functions inside the program?是否可以对带有程序内部功能的可执行文件做同样的事情?

    private Dictionary<string, string> ExternalCommands = new Dictionary<string, string>
    {
        {"help", @".\help.exe"}
    };


    private Dictionary<string, string> InternalFunctions = new Dictionary<string, string>
    {
        **{"exit", function()}**
    };
    public int Execute(string input)
    {
        try
        {
            if (ExternalCommands.Keys.Contains(input))
            {
                var process = new Process();
                process.StartInfo = new ProcessStartInfo(ExternalCommands[input])
                {
                    UseShellExecute = false
                };

                process.Start();
                process.WaitForExit();

                return 0;
            }
            Console.WriteLine($"{input} NOT FOUND");
            return 1;
        }
        catch
        {
            return 1;
        }

How you would do this depends upon the method signatures and what, if any, parameters you need to pass.您将如何执行此操作取决于方法签名以及您需要传递的参数(如果有)。 In general, though, you'd need to create a dictionary of delegates.不过,一般来说,您需要创建一个代表字典。 Action and Func are pretty easy to use in this situation.在这种情况下, ActionFunc很容易使用。

Something like this would work:像这样的东西会起作用:

private void Test()
{
    var commands = new Dictionary<string, Action>();
    commands.Add("exit", Exit);
    commands.Add("greet", SayHello);

    commands["greet"]();
    commands["exit"]();
}

private void Exit()
{
    this.Close();
}

private void SayHello()
{
    MessageBox.Show("Hello!");
}

You could also use lambda expressions to add delegates to such a dictionary for even more flexibility:您还可以使用 lambda 表达式将委托添加到此类字典中,以获得更大的灵活性:

commands.Add("exit", () => this.Close());
commands.Add("greet", () => MessageBox.Show("Hello!"));

For voids you can use Action , if the function has parameters you use Action<T> where T is it the type, for example: Action<string> .对于voids ,您可以使用Action ,如果 function 具有您使用Action<T>的参数,其中 T 是它的类型,例如: Action<string> If your functions return something you can use Func , example for a function which takes a string as an input and returns int : Func<string, int> .如果您的函数返回某些内容,您可以使用Func ,例如 function ,它将string作为输入并返回int : Func<string, int> You can use these as values for the dictionary.您可以将它们用作字典的值。 Here is an example code for a hello world application:下面是一个 hello world 应用程序的示例代码:

    class Program
    {
        public static Dictionary<string, Action> FunctionsInDictionary = new Dictionary<string, Action>()
        {
            { "helloworld", HelloWorld }
        };

        static void Main(string[] args)
        {

            FunctionsInDictionary["helloworld"].Invoke();

            Thread.Sleep(-1);
        }

        static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM