[英]How can I provide default expression in the { } of a lambda expression, while still allowing it to be added to?
I am using the Kendo UI MVC Grid and I want to encapsulate boilerplate code so I don't have to duplicate the same code on every grid. 我正在使用Kendo UI MVC网格,并且想封装样板代码,因此不必在每个网格上重复相同的代码。 Configuring the commands on the grid looks like this:
在网格上配置命令如下所示:
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);
The edit and delete are boilerplate, however there is a potential for extra custom commands depending on the grid. 编辑和删除是样板,但是根据网格,可能会有额外的自定义命令。 The type of the lambda for command is of
Action<GridActionCommandFactory<T>>
. 命令的lambda类型为
Action<GridActionCommandFactory<T>>
。 How can I abstract the boilerplate to a method or something while still allowing custom commands to be entered? 如何在仍然允许输入自定义命令的同时将样板抽象为方法或其他内容? Psuedo-coding it out I figure it would look something like this:
伪编码,我想它看起来像这样:
columns.Command(command =>
{
//Custom commands here
SomeConfigClass.DefaultGridCommands(command);
//Custom commands here
}).Width(130);
or maybe: 或者可能:
columns.Command(command =>
{
//Custom commands here
command.DefaultCommands();
//Custom commands here
}).Width(130);
And this would include the edit and delete commands. 这将包括编辑和删除命令。 But I have no idea how to modify a lambda expression in such a way, how can I achieve this?
但是我不知道如何以这种方式修改lambda表达式,如何实现呢?
Well I did some more digging and it ended up not being that hard. 好吧,我做了更多的挖掘工作,但最终并没有那么努力。 Not sure if it's the most elegant solution but I did it like this:
不知道这是否是最优雅的解决方案,但我这样做是这样的:
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;
}
Then calling it in the grid: 然后在网格中调用它:
columns.Command(KendoUiGridConfig.GetDefaultGridCommands<MyViewModel>()).Width(130);
The Delegate.Combine
method was what I was looking for. 我一直在寻找
Delegate.Combine
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.