【问题标题】:GetEnumerator does not exist in this contextGetEnumerator 在此上下文中不存在
【发布时间】:2015-02-06 16:08:04
【问题描述】:

我已经实现了一个自定义链表,但我在实现 IEnumerator 时遇到了问题。具体来说,编译器告诉我The name "GetEnumerator" does not exist in the current context。我觉得我正在按照我在许多 stackoverflow 帖子和教程中看到的方式实现它,我缺少什么?

这是我的数据结构:

namespace TestReportCreator_v3
{
    public class FindingsTable : IEnumerable<string>
    {
        private Node head, mark;
        public class Node
        {
            public string description; //covers weakness, retinaDesc, nessusDesc
            public string riskLevel; //covers impactLevel, retinaRisk, nessusRisk
            public string boxName; //box name results apply to
            public string scanner; //wassp, secscn, retina, nessus
            public string controlNumber; //ia control number impacted, wassp and secscn only
            public string fixAction; //comments, retinaFix, nessusSolu
            public string auditID; //nessus plugin, retina AuditID, wassp/secscn test number
            public Node next;
            public Node(string auditID, string riskLevel, string boxName, string scanner, string controlNumber, string fixAction, string description, Node next)
            {
                this.description = description;
                this.riskLevel = riskLevel;
                this.boxName = boxName;
                this.scanner = scanner;
                this.controlNumber = controlNumber;
                this.fixAction = fixAction;
                this.auditID = auditID;
                this.next = next;
            }
        }

    ...insert, delete, update, save methods...

        public IEnumerator<string> IEnumerable<string>.GetEnumerator()
        {
            var node = mark;

            while (node != null)
            {
                yield return node.riskLevel;
                node = node.next;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

【问题讨论】:

  • 旁注:奇怪的是编译器在显式接口实现之前没有抱怨public:public IEnumerator&lt;string&gt; IEnumerable&lt;string&gt;.GetEnumerator()
  • 在添加下面答案中的信息后,它确实为公众尖叫。好决定。谢谢。

标签: c# linked-list ienumerable ienumerator


【解决方案1】:

IEnumerable&lt;string&gt;.GetEnumerator() 是显式接口实现,所以需要在实例上调用它,作为接口访问。最简单的方法是投 this:

return ((IEnumerable<string>)this).GetEnumerator();

请参阅How to call explicit interface implementation methods internally without explicit casting? 了解替代方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2021-01-22
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多