迭代器块和inheritance

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

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

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

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

但是,我受到了警告,“无法validation通过迭代器中的base关键字访问成员”。

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

怎么样:

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

顺便提一下,这种奇怪行为的原因是CLR安全团队在v2发布之前就改变了validation者,这使得对来自不同类中的方法的一个类的虚拟方法进行非虚拟调用变得无法validation。

有关此问题的进一步说明,请参阅几年前关于此主题的文章。

http://blogs.msdn.com/ericlippert/archive/2005/11/14/why-are-base-class-calls-from-anonymous-delegates-nonverifiable.aspx

这已经过时了; 我们已经修复了编译器,现在它为你生成帮助器。

这是因为迭代器变成了一个私有类,并且从内部类访问超类方法是不可validation的(因为它必须强制’this’指针指向除了它自己之外的东西)。

尝试在Derived创建一个新的私有方法:

 private IEnumerable GetBaseListOfStuff() { return base.GetListOfStuff(); } 

并调用而不是base.GetListOfStuff()

似乎一个解决方案就是简单地遵循“手册”所说的内容:制作帮手function。

所以现在我已经解决了这个问题:

 public class Derived : Base { private IEnumerable GetBaseStuff() { return base.GetListOfStuff(); } public override IEnumerable GetListOfStuff() { foreach (string s in GetBaseStuff()) { yield return s; } yield return "Fourth"; yield return "Fifth"; } } 

但是,如果它们存在,我对其他解决方案也很好奇。