如何在lambda表达式的{}中提供默认表达式,同时仍允许将其添加到?

时间:2016-11-04 19:53:24

标签: c# linq lambda kendo-ui-mvc kendo-ui-grid

我正在使用Kendo UI MVC Grid,我想封装样板代码,所以我不必在每个网格上复制相同的代码。在网格上配置命令如下所示:

columns.Command(command =>
            {
                command.Custom("Edit").Text("<span class='k-icon k-edit'></span>").Click("editRecord");
                command.Custom("Delete").Text("<span class='k-icon k-i-delete'></span>").Click("deleteItem");
            }).Width(130);

编辑和删除是样板文件,但是根据网格,可能会有额外的自定义命令。命令的lambda类型为Action<GridActionCommandFactory<T>>。如何在仍允许输入自定义命令的同时将样板文件抽象为方法或其他内容? Psuedo编码我认为它看起来像这样:

columns.Command(command =>
            {
                //Custom commands here
                SomeConfigClass.DefaultGridCommands(command);
                //Custom commands here
            }).Width(130);

或者也许:

columns.Command(command =>
            {
                //Custom commands here
                command.DefaultCommands();
                //Custom commands here
            }).Width(130);

这将包括编辑和删除命令。但我不知道如何以这种方式修改lambda表达式,我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

嗯,我做了一些更多的挖掘,结果并没有那么难。不确定它是否是最优雅的解决方案,但我是这样做的:

public static Action<GridActionCommandFactory<T>> GetDefaultGridCommands<T>(Action<GridActionCommandFactory<T>> customCommandsBeforeDefault = null, Action<GridActionCommandFactory<T>> customCommandsAfterDefault = null) where T : class
    {
        Action<GridActionCommandFactory<T>> defaultCommands = x =>
        {
            x.Custom("Edit").Text("<span class='k-icon k-edit'></span>").Click("editRecord");
            x.Custom("Delete").Text("<span class='k-icon k-i-delete'></span>").Click("deleteItem");
        };

        List<Action<GridActionCommandFactory<T>>> actions = new List<Action<GridActionCommandFactory<T>>>();

        if(customCommandsBeforeDefault != null)
            actions.Add(customCommandsBeforeDefault);
        actions.Add(defaultCommands);
        if(customCommandsAfterDefault != null)
            actions.Add(customCommandsAfterDefault);

        Action<GridActionCommandFactory<T>> combinedAction = (Action<GridActionCommandFactory<T>>) Delegate.Combine(actions.ToArray());

        return combinedAction;
    }

然后在网格中调用它:

columns.Command(KendoUiGridConfig.GetDefaultGridCommands<MyViewModel>()).Width(130);

我正在寻找Delegate.Combine方法。