将一组 yield return 语句重构为一个方法

Refactoring group of yeild return statments to a method

我如何将多个 yield 语句分组到一个方法中?

我有以下代码:

public IEnumerable<IPublisher> RegisterEvents()
{
    var url= Settings.wcfUrl;
    var publisher = PublisherFactory.Create<IWcfPublisher> (url)
        publisher.Register(new object(..));
        publisher.Register(new object(..));
     yield return publisher;

    var url = Settings.webpublisherurl;
    var publisher = PublisherFactory.Create<IWebPublisher> (url)
        publisher.Register(new object(..));
        publisher.Register(new object(..));
     yield return publisher;

    var url = Settings.webpublisherurl2;
    var publisher = PublisherFactory.Create<IWebPublisher2> (url)
        publisher.Register(new object(..));
        publisher.Register(new object(..));
     yield return publisher;
     . . .
}

代码变得非常大,我想将一些发布者重构为静态 class EventHelper

public IEnumerable<IPublisher> RegisterEvents()
{
    var url= Settings.wcfUrl;
    var publisher = PublisherFactory.Create<IWcfPublisher> (url)
        publisher.Register(new object(..));
        publisher.Register(new object(..));
     yield return publisher;

    return yield EventHelper.CreateWebApiPublisher() //<-- compiler error
     . . .
}

CreateWebApiPublisher() 看起来像

public static IEnumerable<IPublisher> CreateWebApiPublisher()
{
    var url = Settings.webpublisherurl;
    var publisher = PublisherFactory.Create<IWebPublisher>(url)
    publisher.Register(new object(..));
    publisher.Register(new object(..));
    yield return publisher;

    var url = Settings.webpublisherurl2;
    var publisher = PublisherFactory.Create<IWebPublisher2>(url)
    publisher.Register(new object(..));
    publisher.Register(new object(..));
    yield return publisher;
}

我很困惑如何在 RegisterEvents() 中使用 EventHelper.CreateWebApiPublisher() 我不断收到编译器错误:

Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<IPublisher>' to 'IPublisher'...

将函数的 return 类型更改为 IPublisher 而不是可枚举类型,并且不要屈服。你的函数应该只有 return 个,然后你就可以 yield 调用了。将任何要求作为参数传递。

yield return 一次只能产生一个值。在出现编译器错误的那一行,您需要遍历该方法的结果,并按顺序 yield return 它们。

foreach (var p in EventHelper.CreateWebApiPublisher())
    yield return p;