在字典C#存储功能 [英] C# Store functions in a Dictionary

查看:319
本文介绍了在字典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>>

这允许你存储在字符串中的功能和返回boolean值。

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是这样定义的:

where Foo is defined like this:

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&LT;&GT; 而不是 System.Func&LT;&GT;

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天全站免登陆