迭代器块和继承 [英] Iterator blocks and inheritance

查看:102
本文介绍了迭代器块和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定具有以下接口的基类:

Given a base class with the following interface:

public class Base
{
    public virtual IEnumerable<string> GetListOfStuff()
    {
        yield return "First";
        yield return "Second";
        yield return "Third";
    }
}

我想创建一个覆盖方法的派生类,并添加自己的东西,如下:

I want to make a derived class that overrides the method, and adds its own stuff, like so:

public class Derived : Base
{
    public override IEnumerable<string> GetListOfStuff()
    {
        foreach (string s in base.GetListOfStuff())
        {
            yield return s;
        }

        yield return "Fourth";
        yield return "Fifth";
    }
}

然而,我受到了警告无法通过迭代器中的base关键字访问成员。

However, I'm greeted with a warning that "access to a member through a base keyword from an iterator cannot be verified".

这个问题的解决方案是什么?

What's the accepted solution to this problem then?

推荐答案

怎么样:

public class Derived : Base
{
    public override IEnumerable<string> GetListOfStuff()
    {
        return base.GetListOfStuff().Concat(GetMoreStuff());        
    }
    private IEnumerable<string> GetMoreStuff()
    {
        yield return "Fourth";
        yield return "Fifth";
    }
}

这篇关于迭代器块和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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