2016-11-09 61 views
-2

我有这样了解懒评价在C#

class Context 
    { 
     public List<Student> lists; 
     public Context() 
     { 
      lists = new List<Student>() { 
       new Student { Name="foo",Standard="first",subjects=new Subjects { Geography=50,History=81,Science=70} }, 
       new Student { Name="carl",Standard="first",subjects=new Subjects { Geography=40,History=51,Science=50} }, 
       new Student { Name="ben",Standard="first",subjects=new Subjects { Geography=30,History=91,Science=60} }, 
       new Student { Name="peter",Standard="first",subjects=new Subjects { Geography=80,History=71,Science=40} }    
      }; 
     } 
    } 
    class Client 
    { 
     static void Main(string[] args) 
     { 
      List<Student> lists = new Context().lists; 
      var result = lists.Where(x => x.subjects.History > 60); 
      lists.Add(new Student { Name = "tan", Standard = "first", subjects = new Subjects { Geography = 40, History = 81, Science = 60 } }); 
      lists.Add(new Student { Name = "ran", Standard = "first", subjects = new Subjects { Geography = 30, History = 70, Science = 50 } }); 
      lists.Add(new Student { Name = "ranky", Standard = "first", subjects = new Subjects { Geography = 20, History = 31, Science = 40 } }); 
      lists.Add(new Student { Name = "franky", Standard = "first", subjects = new Subjects { Geography = 50, History = 51, Science = 30 } }); 
      foreach (var data in result) { 
      Console.WriteLine(data); 
     } 
     } 
    } 

现在代码在调试时,加入一些元素,当我把鼠标放在变量之前,我得到这样

enter image description here

结果

加入一些元素的名单后,当我将鼠标悬停在变量i得到这样

enter image description here结果 ,但根据懒惰执行的概念,当它到达foreach方法时加载数据,那么为什么数据已经加载并在调试器中看到。我是否理解懒惰评估 更新1 根据以前关于我的截图,如果点击“结果视图”强制加载数据,那么,这里是我第二个场景,我只是加载数据,可以看到形成屏幕截图

enter image description here 但是当调试器移动到下一个元素时,计数会增加。

enter image description here 是不是假设使用foreach进行调用时加载数据?请帮助我了解懒惰评估的工作原理。谢谢。

+1

你在你的问题所引用的代码看上去一点也不像截图你已经展示过。请提供一个[mcve],并显示来自*的输出*(可以再次显示文本 - 根本不需要截图) –

+0

好吧,只需一秒...感谢您的帮助 –

+2

'Concat'不会修改数字,它会返回一个新的被修改的列表。你可能想要'result = numbers.Concat(num2);'来代替'numbers.Concat(num2);'。 – Quantic

回答

2

这是因为你并没有使用拼接的结果,任何事情:

numbers.Concat(num2); 

这应该是:

numbers = numbers.Concat(num2).ToArray(); 
+0

这将不会编译,因为'数字'被键入为'int []'而不是'IEnumerable '。 –

+0

@MichaelLiu请尝试你会惊讶的代码 –

+0

@MichaelLiu你是对的,谢谢。我修复了它。 – itsme86