简体   繁体   English

我将如何创建ReturnAlteredObject扩展方法?

[英]How would I go about creating a ReturnAlteredObject extension method?

TL;DR: I want an extension method that can extend object and can be used like this: TL; DR:我想要一个扩展方法,该方法可以扩展对象并且可以像这样使用:

var OtherInstance = MyObject.Altered(new { Prop1 = "123", Prop6 = 4 });

I'd expect all properties of OtherInstance to be the same as MyObject , except for Prop1 and Prop6 . 除了Prop1Prop6外,我希望OtherInstance所有属性都与MyObject相同。 I don't expect/require it to deep-clone. 我不希望/不需要它进行深度克隆。


Background 背景

I have an MVC page that allows the user to search to display a list of data. 我有一个MVC页面,允许用户搜索以显示数据列表。

My page model has various filter properties, as well as a page number. 我的页面模型具有各种过滤器属性以及页码。

At the bottom of my list of data I have a link to the next page created using Html.ActionLink . 在数据列表的底部,有一个指向使用Html.ActionLink创建的下一页的链接。 I pass in a copy of the model, with the page number incremented: 我传入了模型的副本,页面编号增加了:

<%= Html.ActionLink("Next", "Index", new
{
    Page = (Model.Page ?? -1) + 1,
    Model.SortProperties,
    Model.SortDescending,
    Model.FilterId,
    Model.FilterApprovalsLevelId,
    Model.FilterStandardTypeId,
    Model.FilterApprovalsBodyReferenceNumber,
    Model.FilterCertificateOrApprovalNumber
}, new { id = "next-page" })%>

If I add new filters to my model it's easy to forget to add the property in here, so I was hoping to be able to clone the object and alter 1 or 2 properties fluently, like so: 如果我在模型中添加新的过滤器,很容易忘记在此处添加属性,因此我希望能够克隆对象并流畅地更改1或2个属性,如下所示:

<%= Html.ActionLink("Next", "Index", Model.Altered(new
{
    Page = (Model.Page ?? -1) + 1
}), new { id = "next-page" })%>

You can use RouteValueDictionary class to achive that. 您可以使用RouteValueDictionary类实现这一点。 First Create and instance of RouteValueDictionary from your model and then add to the dictionary the rest of the properties here is the pseudo code: 首先从模型中创建RouteValueDictionary的实例,然后将其余的属性添加到字典中,这里是伪代码:

<%= Html.ActionLink("Next", "Index", new RouteValueDictionary(Model).AddAndReturn("Page", (Model.Page ?? -1) + 1), new { id = "next-page" })%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM