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

How can I provide default expression in the { } of a lambda expression, while still allowing it to be added to?

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

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>>。我怎样才能将样板抽象为方法或其他东西,同时仍然允许输入自定义命令?伪编码出来我认为它看起来像这样:

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 表达式,我该如何实现?

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

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 方法正是我要找的。