c# - 迭代器 block 和继承

标签 c# inheritance iterator

给定一个具有以下接口(interface)的基类:

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

我想创建一个重写方法的派生类,并添加自己的东西,如下所示:

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

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

但是,我收到警告“无法验证通过迭代器中的基本关键字访问成员”。

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

最佳答案

怎么样:

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

关于c# - 迭代器 block 和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2432821/

相关文章:

c# - 如何使用 dotnet test 命令行运行单个 xunit C# 测试

c# - 通过禁用匿名身份验证来解决 WCF REST 服务问题

Scala 案例类继承

python - 如何读取文件的第一行两次?

c# - 使用 XML(HTML) 转义的 Unicode 到 Windows-1251 的转换

c# - javascript 元素的大小无法正常工作

Java 泛型不能对泛型 T 使用通配符

javascript - 继承的 Angular 2 组件中的输入属性

C++ "vector iterator not dereferencable"在运行时

iterator - 这是迭代一组值的规范方法吗?