'yield return'语句不能出现在try/catch块约束中
问题描述:
这两种方法实际上是相同的,但第一种不能编译.我不知道存在此约束的原因
These two methods are practically the same, yet the first one can't compile. I can't figure out the reason this constraint exists
/// <summary>
/// Dynamically loads all document extractors from implementation assemblies into an enumeration
/// </summary>
private static IEnumerable<IDocumentExtractor> EnumerateInstances()
{
IEnumerable<Type> types = EnumerateTypes();
foreach(Type type in types)
{
try
{
IDocumentExtractor extractor = Activator.CreateInstance(type) as IDocumentExtractor;
yield return extractor;
}
catch
{
_log.WarnFormat("Type {0} couldn't be instanced.", type.Name);
}
}
}
实际上可以毫无问题地编译的版本:
And the version that actually compiles without issues:
/// <summary>
/// Dynamically loads all document extractors from implementation assemblies into an enumeration
/// </summary>
private static IEnumerable<IDocumentExtractor> EnumerateInstances()
{
IEnumerable<Type> types = EnumerateTypes();
foreach (Type type in types)
{
IDocumentExtractor extractor = null;
try
{
extractor = Activator.CreateInstance(type) as IDocumentExtractor;
}
catch
{
_log.WarnFormat("Type {0} couldn't be instanced.", type.Name);
}
if (extractor != null)
yield return extractor;
}
}
答
您可以在Eric Lippert关于迭代器块的系列文章中获得此问题的答案.具体查看标题为迭代器块,第五部分:推入与拉出.分为七个部分的系列开始于迭代器块,第一部分.
You can get the answer to this question in Eric Lippert's series on Iterator Blocks. Specifically check out the post titled Iterator Blocks, Part Five: Push vs Pull. The seven-part series starts with Iterator Blocks, Part One.