问题描述
我在使用yield return
的方法上遇到了一些麻烦,这不起作用...
I'm having a little trouble with a method in which I use yield return
this doesn't work...
public IEnumerable<MyClass> SomeMethod(int aParam)
{
foreach(DataRow row in GetClassesFromDB(aParam).Rows)
{
yield return new MyClass((int)row["Id"], (string)row["SomeString"]);
}
}
上面的代码永远不会运行,当调用此方法时,它只会越过它.
The above code never runs, when the call is made to this method it just steps over it.
但是,如果我更改为...
However if I change to...
public IEnumerable<MyClass> SomeMethod(int aParam)
{
IList<MyClass> classes = new List<MyClass>();
foreach(DataRow row in GetClassesFromDB(aParam).Rows)
{
classes.Add(new MyClass((int)rows["Id"], (string)row["SomeString"]);
}
return classes;
}
它很好用.
我不明白为什么第一种方法永远不会运行,您能帮助我了解这里发生的事情吗?
I don't understand why the first method never runs, could you help me in understanding what is happening here?
推荐答案
仅当调用者实际上开始枚举返回的集合时,"yield"版本才是"run".
The "yield" version is only "run" when the caller actually starts to enumerate the returned collection.
例如,如果您仅获得集合:
If, for instance, you only get the collection:
var results = SomeObject.SomeMethod (5);
并且不执行任何操作,SomeMethod
将不会执行.
and don't do anything with it, the SomeMethod
will not execute.
只有当您开始枚举results
集合时,它才会命中.
Only when you start enumerating the results
collection, it will hit.
foreach (MyClass c in results)
{
/* Now it strikes */
}
这篇关于使用收益回报时未调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!