在lambda甚至定义之前准备一个引用lambda变量的对象

时间:2015-03-09 10:18:40

标签: c# lambda

此助手输出分页:

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        new { 
            page = index, 
            amount = 10, 
            sort = Request.Params[ "sort" ], 
            order = Request.Params[ "order" ] 
        } 
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

BootstrapPager函数的第二个参数是lambda。 index变量引用了输出页码的内部循环。

有什么方法你可以想到这允许我预先准备传入的对象作为仍然引用lambda Url.Action变量的index的第3个参数吗?

可能看起来像这样:

object myActionData = new { 
    page = <index>, // I don't know how this line would work
    amount = 10, 
    sort = Request.Params[ "sort" ], 
    order = Request.Params[ "order" ] 
}    

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        myActionData        
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

1 个答案:

答案 0 :(得分:4)

这是不可能的,这里有一个lambda的重点是在有效调用lambda之前没有设置index

您可以做的最好是事先声明工厂功能。

@{
    Func<int, object> myActionDataFactory = index => new { 
        page = index, // Here we use the parameter
        amount = 10, 
        sort = Request.Params[ "sort" ], 
        order = Request.Params[ "order" ] 
    };
}

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    index => Url.Action( 
        "List", 
        "Test", 
        myActionDataFactory(index)
    ),
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
) 

同样,您可以从BootstrapPager调用中删除整个lambda。

@{
    Func<int, sting> myUrlFactory = index => Url.Action( 
            "List", 
            "Test",
            new { 
                page = index, // Here we use the parameter                
                amount = 10, 
                sort = Request.Params[ "sort" ], 
                order = Request.Params[ "order" ] 
            });
}

@Html.BootstrapPager( 
    int.Parse( Request.Params[ "page" ] ), 
    myUrlFactory,
    Model.PaginationSet.TotalItemCount, 
    numberOfLinks: 10 
)

您甚至可以将您的Url工厂声明为您在代码中其他位置声明的(可能是静态的)类的方法。

相关问题