关于 new { } 使用的问题
我目前正在阅读 Apress ASP.NET MVC2 书,对于以下代码中 new { returnUrl } 的用户有点困惑:
public RedirectToRouteResult RemoveFromCart(Cart cart, int productID, string returnUrl)
{
Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);
cart.RemoveLine(product);
return RedirectToAction("Index", new { returnUrl });
}
这与创建有关吗?一个新字符串,而不是简单地传递对传入参数的引用?
I am currently working my way through the Apress ASP.NET MVC2 book, and I am a little bit confused as to the user of new { returnUrl } in the following code:
public RedirectToRouteResult RemoveFromCart(Cart cart, int productID, string returnUrl)
{
Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);
cart.RemoveLine(product);
return RedirectToAction("Index", new { returnUrl });
}
Is it something to do with creating a new string, rather than simply passing a reference to the parameter passed in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它创建一个带有属性
returnUrl
的匿名类型,该属性也具有returnUrl
的值。所以它是这样的:使用表达式中的名称来确定匿名类型中的属性名称称为投影初始值设定项。
这对向你解释有帮助吗?如果没有,您可能需要总体修改匿名类型。它们是在 C# 3 中引入的,主要用于 LINQ。
It's creating an anonymous type with a property
returnUrl
which also has the value ofreturnUrl
. So it's like this:Using a name from the expression to determine the name of the property in an anonymous type is called a projection initializer.
Does that help to explain it to you at all? If not, you may want to revise anonymous types in general. They were introduced in C# 3, mostly for LINQ.
这是匿名类型: http://msdn.microsoft.com/en-us /library/bb397696.aspx
This is an anonymous type: http://msdn.microsoft.com/en-us/library/bb397696.aspx
那是一个匿名对象。上面例子中的属性将创建一个带有字符串属性“returnUrl”的新对象。
在此上下文中,它指定 ActionResult 将浏览器重定向到的 url。
That is an anonymous object. The property in the case above would create a new object with the string property 'returnUrl'.
In this context, it is specifying a url for the ActionResult to redirect the browser to.
该语法创建一个匿名类型。它们是根据需要动态创建的。在您的示例中,它创建一个具有一个属性的新对象,然后将其作为参数传递给操作。
That syntax creates an anonymous type. They're created on the fly as needed. In your example it creates a new object with one property and then passes it to the action as a parameter.