'yield return'语句不能出现在try/catch块约束中 [英] 'yield return' statement can't appear in try/catch block constraint

查看:39
本文介绍了'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.

这篇关于'yield return'语句不能出现在try/catch块约束中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆