【问题标题】:Using lambda for builder pattern将 lambda 用于构建器模式
【发布时间】:2012-07-10 07:13:49
【问题描述】:

telerik 网格在绑定到列时使用 lambda 语法来增强构建器模式。

.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");
        });
    }
}

【问题讨论】:

    标签: c# lambda telerik builder


    【解决方案1】:

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

    // 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();
    }
    

    【讨论】:

    • 嗯,可能是这个,让我测试一下。
    • 所以在我上面的例子中,我需要在 SubList 中实现类似于您的 Columns 方法的 'Sub()' 方法?
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 2017-08-30
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2014-11-23
    相关资源
    最近更新 更多