简体   繁体   English

为什么在DisplayNameFor()中需要lambda表达式?

[英]Why is the lambda expression necessary in DisplayNameFor()?

For the example code: 对于示例代码:

<th>@Html.DisplayNameFor(model => model.Artist.Name)</th>

Why is the lambda expression necessary at all? 为什么根本需要lambda表达式? Why can't it just be 为什么不能只是

<th>@Html.DisplayNameFor(model.Artist.Name)</th>

This is trickery using expression trees. 这是使用表达式树的骗术。

The first constructs an expression tree at runtime, allowing the method to go in and find the member being accessed (and thus get all of its attributes). 第一种在运行时构造一个表达式树,允许该方法进入并找到要访问的成员(从而获得其所有属性)。

The second would simply pass the value of Name into the method. 第二种方法只是将Name的值传递给方法。

Remember that your model is simply a definition of your general data structure, and this is bound at runtime to determine what the actual values of the model should be set to, dependent on the parameters being used to access the data. 请记住,您的模型只是简单的通用数据结构的定义,在运行时必须绑定它,以确定模型的实际值,具体取决于用于访问数据的参数。

What you're seeing is just the way that the DisplayNameFor method is defined in order for this to happen, and your 2nd line of code is simply invalid. 您所看到的只是为了执行此操作而定义DisplayNameFor方法的方式,并且第二行代码完全无效。 DisplayNameFor is an extension method of the HTML helper, and accepts as a single parameter a lambda expression that identifies the model and the property of the model that you want to display, so that the actual data retrieval can occur at runtime. DisplayNameFor是HTML帮助器的扩展方法,它接受lambda表达式作为单个参数,该表达式标识模型和要显示的模型的属性,以便可以在运行时进行实际的数据检索。 See here for the formal definition of the method: 有关方法的正式定义,请参见此处:

https://msdn.microsoft.com/en-us/library/hh833697(v=vs.118).aspx https://msdn.microsoft.com/zh-CN/library/hh833697(v=vs.118).aspx

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

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