简体   繁体   English

检查和评估之间有什么区别?

[英]What is the difference between inspection and evaluation?

I am going through the Razor tutorial on Microsoft Docs and came across a lambda expression used in an HTML helper: 我正在阅读有关Microsoft Docs的Razor教程,并遇到了HTML帮助器中使用的lambda表达式:

@Html.DisplayNameFor(model => model.Movie[0].Title))

Movie is of type IList< Movie >, where Movie is a class created in the tutorial. Movie是IList <Movie>类型的,其中Movie是在教程中创建的类。 The author states that: 作者指出:

" DisplayNameFor HTML Helper inspects the Title property referenced in the lambda expression to determine the display name. The lambda expression is inspected rather than evaluated . That means there is no access violation when Movie[0] is null or empty." DisplayNameFor HTML Helper将检查 lambda表达式中引用的Title属性来确定显示名称。lambda表达式将被检查而不是被求值 。这意味着Movie [0]为null或为空时不存在访问冲突。”

I understand inspection from intuition but how does this differ from say: 我从直觉上了解检查,但这与说的有何不同:

Console.WriteLine(Movie[0].Title)

if the HTML helper sees an empty List there is no issue but if the console method sees an empty list an exception will be thrown. 如果HTML帮助程序看到一个空列表,则没有问题,但是,如果控制台方法看到一个空列表,则将引发异常。

The only way I could guess at how this works is that behind the scenes there is a try / catch at work. 我只能猜测这种工作方式的唯一方法是在幕后进行尝试/捕获。

Display Name means either the name of the property itself, ie "Title" , or the string value defined in the Display attribute on the property, if the property has one, ie: 显示名称表示属性本身的名称 (即"Title" ,或者表示在属性的Display属性中定义的字符串值(如果属性具有一个名称),即:

public class Movie
{
    [Display(Name = "Movie Title")]
    public string Title { get; set; }
}

We can see it doesn't care about the Title property's value , so it never needs to evaluate it, therefore it won't throw if the movie is null. 我们可以看到它并不关心Title属性的 ,因此它不需要评估它,因此如果电影为null则不会抛出该值。

Just want to add few things to Saeb Amini's answer. 只想在Saeb Amini的答案中添加一些内容。

  1. It's always good idea to check Microsoft reference source or one of the open source version of code available to get hint of how it is working behind the scene. 检查Microsoft参考源或可用的开放源代码版本之一来暗示它在后台的工作方式总是一个好主意。 Visit the source 访问源
  2. By Looking at the source you will see, the framework is not accessing the object it self but uses Metadata from the expression it self to get Display name of the property in expression so it will not result in any exception even if object is null. 通过查看源代码,您将看到框架未访问其自身的对象,而是使用其自身的表达式中的Metadata来获取表达式中属性的显示名称,因此即使object为null,也不会导致任何异常。

Finally, To answer your question, evaluation is when you actually evaluate lamda expression for the result (invocation) while inspection is when you inspect various attributes of the lamda expression. 最后,要回答您的问题,评估是指您实际评估结果(调用)的lamda表达式,而检查则是检查lamda表达式的各种属性。

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

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