如何在lambda表达式的{}中提供默认表达式,同时仍然允许将其添加到
本文关键字:表达式 添加 默认 lambda | 更新日期: 2023-09-27 18:16:35
我正在使用剑道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 for命令的类型为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
方法是我正在寻找的。