C# 在字典中存储函数 [英] C# Store functions in a Dictionary

查看:98
本文介绍了C# 在字典中存储函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个可以存储函数的字典?

How do I create a Dictionary where I can store functions?

谢谢.

我有大约 30 多个可以由用户执行的功能.我希望能够以这种方式执行该功能:

I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:

   private void functionName(arg1, arg2, arg3)
   {
       // code
   }

   dictionaryName.add("doSomething", functionName);

    private void interceptCommand(string command)
    {
        foreach ( var cmd in dictionaryName )
        {
            if ( cmd.Key.Equals(command) )
            {
                cmd.Value.Invoke();
            }
        }
    }

然而,函数签名并不总是相同的,因此具有不同数量的参数.

However, the function signature is not always the same, thus having different amount of arguments.

推荐答案

像这样:

Dictionary<int, Func<string, bool>>

这允许您存储接受字符串参数并返回布尔值的函数.

This allows you to store functions that take a string parameter and return boolean.

dico[5] = foo => foo == "Bar";

或者如果函数不是匿名的:

Or if the function is not anonymous:

dico[5] = Foo;

Foo 定义如下:

public bool Foo(string bar)
{
    ...
}

<小时>

更新:

在看到您的更新后,您似乎事先不知道要调用的函数的签名.在 .NET 中,为了调用一个函数,您需要传递所有参数,如果您不知道参数是什么,那么实现这一点的唯一方法就是通过反射.

After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.

这是另一种选择:

class Program
{
    static void Main()
    {
        // store
        var dico = new Dictionary<int, Delegate>();
        dico[1] = new Func<int, int, int>(Func1);
        dico[2] = new Func<int, int, int, int>(Func2);

        // and later invoke
        var res = dico[1].DynamicInvoke(1, 2);
        Console.WriteLine(res);
        var res2 = dico[2].DynamicInvoke(1, 2, 3);
        Console.WriteLine(res2);
    }

    public static int Func1(int arg1, int arg2)
    {
        return arg1 + arg2;
    }

    public static int Func2(int arg1, int arg2, int arg3)
    {
        return arg1 + arg2 + arg3;
    }
}

使用这种方法您仍然需要知道需要传递给字典相应索引处的每个函数的参数的数量和类型,否则您将得到运行时错误.如果您的函数没有返回值,请使用 System.Action<> 而不是 System.Func<>.

With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.

这篇关于C# 在字典中存储函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆