请考虑以下代码:
public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
for (int k = 0; MajicNumber(ref k, amount); )
{
yield return CalculateStats(ticker, equity, k);
// Can we get the value of current resultset here?
}
}
由于函数维护结果集,我们可以访问吗?
传统的对应方是:
public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
List<float> resultSet = new List<float>();
for (int k = 0; MajicNumber(ref k, amount); )
{
resultSet.Add(CalculateStats(ticker, equity, k));
// resultSet is accessible here
}
return resultSet;
}
答案 0 :(得分:3)
当然,你可以做到。第二个代码段中的逻辑没有太大变化,除了你找到答案时yield return
:
public static IEnumerable<float> Power(string ticker, float equity, float amount)
{
IList<float> resultSet = new List<float>();
for (int k = 0; MajicNumber(ref k, amount); )
{
float r = CalculateStats(ticker, equity, k);
resultSet.Add(r);
yield return r;
}
}
答案 1 :(得分:3)
由于函数维护结果集,我们可以访问吗?
不,迭代器块不维护任何结果集。