c# - 使用 lambda 构建器模式

标签 c# lambda telerik builder

Telerik 网格使用 lambda 语法来增强绑定(bind)到列时的构建器模式。

.Columns(cols =>
    {
        cols.Bound(e => e.Tag);
        cols.Bound(e => e.Name);
     });

我想在我的代码中创建类似的函数。我已经掌握了 Bound() 函数的语法。但是 Columns() 函数的语法是什么样的?

这是我想要实现的更好的示例:

class SubList
{
    private List<string> _items;

    public AddItem(string item)
    {
        _items.Add(item);
    }
}

class MyCollections
{
    private Dictionary<string, SubList> _subs = new Dictionary<string,SublList>();

    public SubList AddList(string name)
    {
        var newSub = new SubList();
        _subs[name] = newSub;
        return newSub;
    }
}

class Other
{
    public void DoStuff()
    {
        var collections = new MyCollections();

        //if add item throws error, I don't know which one it is as.
        //it is also hard to put a break point in here.
        collections.AddList("one")
            .AddItem("1")
            .AddItem("un")
            .AddItem("uno");

        //I would like to have something like this:
        collections.AddList("two") { s =>
            s.AddItem("1");
            s.AddItem("un"); //yay! can put breakpoint here
            s.AddItem("uno");
        };

        //or perhaps
        collections.AddList("two").Sub( s => {
            s.AddItem("1");
            s.AddItem("un"); //yay! can put breakpoint here
            s.AddItem("uno");
        });
    }
}

最佳答案

它可以是扩展方法或实例方法,可能如下:

// Assuming some grid type TDataGrid and some column building type TColumnBuilder
public TDataGrid Columns(Action<TColumnBuilder> applyColumns)
{
    // Ask the user what they'd like to do with our columns
    TColumnBuilder placeholder = new TColumnBuilder();
    applyColumns(placeholder);

    // do something with what we've learned
    // this.columns = placeholder.CreateColumns();
}

关于c# - 使用 lambda 构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11419612/

相关文章:

f# - F#中的传递函数

asp.net-mvc - 剑道网格 : Foreign Key Dropdown does not update grid cell after update

asp.net - Telerik radGrid - 当数据源=数据集时可以使用AllowAutomaticUpdates吗?

javascript - 对于使用 XMLHttpRequest 更改其内容的页面来说,合适的事件监听器是什么?

c# - 将自定义颜色添加到 Color 结构?

c# - Windows 窗体 DateTimePicker 始终打开

javascript - 阻止页面回发的“未指定错误”

c# - 如何在 Windows Phone 8.1 中显示模态窗体

python - 如何在 Python 2.7 中创建 Lambda 函数来创建、重新启动、删除、修改 ElastiCache Redis?

c++ - 使用 lambda 表达式作为 std::set 的比较,当它在 vector 中时