如何在C#中使用通用的IEnumerable接口。

huangapple go评论57阅读模式
英文:

how to use generic IEnumerable Interface in c#

问题

我正在尝试使用通用版本设置支持IEnumerable的类。以下是我的代码:

internal class Mailboxes : IEnumerable<Mailbox>
{
    List<Mailbox> MailboxesList = new List<Mailbox>();

    void AddMailbox(Mailbox mailbox)
    {
        MailboxesList.Add(mailbox);
    }

    public IEnumerator<Mailbox> GetEnumerator()
    {
        return MailboxesList.GetEnumerator();
    }
}

我在GetEnumerator()行收到以下错误信息:

错误 CS0738 'Mailboxes'未实现接口成员'IEnumerable.GetEnumerator()'。'Mailboxes.GetEnumerator()'无法实现'IEnumerable.GetEnumerator()',因为它的返回类型不匹配'IEnumerator'。

有人可以解释我做错了什么吗?谢谢。

英文:

I'm trying to setup a class supporting IEnumerable using the Generic version. Heres my code

	internal class Mailboxes : IEnumerable&lt;Mailbox&gt;
	{
		List&lt;Mailbox&gt; MailboxesList = new List&lt;Mailbox&gt;();

		void AddMailbox(Mailbox mailbox)
		{
			return MailboxesList.Add(mailbox);
		}

		public IEnumerator&lt;Mailbox&gt; GetEnumerator()
		{
			return MailboxesList.GetEnumerator();
				}

	}

I get this error pointing to the GetEnumerator() line:
> Severity Code Description Project File Line Suppression State
Error CS0738 'Mailboxes' does not implement interface member 'IEnumerable.GetEnumerator()'. 'Mailboxes.GetEnumerator()' cannot implement 'IEnumerable.GetEnumerator()' because it does not have the matching return type of 'IEnumerator'.

Can someone explain what I am doing wrong? Thanks

答案1

得分: 1

你需要实现非泛型版本(因为泛型版本声明为 public interface IEnumerable&lt;out T&gt; : IEnumerable),通常可以通过显式接口实现来完成:

internal class Mailboxes : IEnumerable&lt;Mailbox&gt;
{
    List&lt;Mailbox&gt; MailboxesList = new List&lt;Mailbox&gt;();

    void AddMailbox(Mailbox mailbox)
    {
        MailboxesList.Add(mailbox);
    }

    public IEnumerator&lt;Mailbox&gt; GetEnumerator() =&gt; MailboxesList.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() =&gt; MailboxesList.GetEnumerator();
}
英文:

You need to implement non-generic version too (since the generic one declared as public interface IEnumerable&lt;out T&gt; : IEnumerable), usually it is done via explicit interface implementation:

internal class Mailboxes : IEnumerable&lt;Mailbox&gt;
{
    List&lt;Mailbox&gt; MailboxesList = new List&lt;Mailbox&gt;();

    void AddMailbox(Mailbox mailbox)
    {
        MailboxesList.Add(mailbox);
    }

    public IEnumerator&lt;Mailbox&gt; GetEnumerator() =&gt; MailboxesList.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() =&gt; MailboxesList.GetEnumerator();
}

huangapple
  • 本文由 发表于 2023年7月27日 19:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定