在" 我如何仅公开IList的片段<>问题"中,其中一个答案包含以下代码段:
IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
Run Code Online (Sandbox Code Playgroud)
yield关键字有什么作用?我已经看到它在几个地方被引用,另外一个问题,但我还没弄清楚它实际上做了什么.我习惯于在一个线程产生另一个线程的意义上考虑收益率,但这似乎并不重要.
这个问题在这里已经有了答案:
在返回IEnumerable时是否有理由不使用'yield return'?
关于这些的好处,这里有几个有用的问题yield return.例如,
我正在寻找关于何时不使用的想法yield return.例如,如果我预计需要返回一个集合中的所有项目,它没有看起来就像yield是有用的,对不对?
什么情况下使用yield会限制,不必要,让我陷入困境,或者应该避免?
好吧,当我在构建一个自定义枚举器时,我注意到了这种与收益率有关的行为
说你有这样的事情:
public class EnumeratorExample
{
public static IEnumerable<int> GetSource(int startPoint)
{
int[] values = new int[]{1,2,3,4,5,6,7};
Contract.Invariant(startPoint < values.Length);
bool keepSearching = true;
int index = startPoint;
while(keepSearching)
{
yield return values[index];
//The mind reels here
index ++
keepSearching = index < values.Length;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在技术上从函数返回之后,是什么让编译器的底层可以执行索引++和while循环中的其余代码?
我访问了不同的网站,试图了解使用自定义枚举的实时示例,我正在放弃这一行.我有例子.但他们让我感到困惑.
例
拿1
class NumberArray
{
public int[] scores;
public NumberArray()
{
}
public NumberArray(int[] scores)
{
this.scores = scores;
}
public int[] Scores
{
get {return scores;}
}
}
Run Code Online (Sandbox Code Playgroud)
拿2
public class Enumerator : IEnumerator
{
int[] scores;
int cur;
public Enumerator(int[] scores)
{
this.scores = scores;
cur = -1;
}
public Object Current
{
get {
return scores[cur];
}
}
public void Reset()
{
cur = -1;
}
public bool MoveNext()
{
cur++;
if (cur < scores.Length)
return …Run Code Online (Sandbox Code Playgroud)