您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C#在字典中存储函数

C#在字典中存储函数

像这样:

Dictionary<int, Func<string, bool>>

这使您可以存储带有字符串参数并返回布尔值的函数

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

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

dico[5] = Foo;

Foo的定义如下:

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

更新:

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

这是另一种选择:

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<>

c# 2022/1/1 18:22:29 有420人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶