英文:
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<Mailbox>
{
List<Mailbox> MailboxesList = new List<Mailbox>();
void AddMailbox(Mailbox mailbox)
{
return MailboxesList.Add(mailbox);
}
public IEnumerator<Mailbox> 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<out T> : IEnumerable
),通常可以通过显式接口实现来完成:
internal class Mailboxes : IEnumerable<Mailbox>
{
List<Mailbox> MailboxesList = new List<Mailbox>();
void AddMailbox(Mailbox mailbox)
{
MailboxesList.Add(mailbox);
}
public IEnumerator<Mailbox> GetEnumerator() => MailboxesList.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => MailboxesList.GetEnumerator();
}
英文:
You need to implement non-generic version too (since the generic one declared as public interface IEnumerable<out T> : IEnumerable
), usually it is done via explicit interface implementation:
internal class Mailboxes : IEnumerable<Mailbox>
{
List<Mailbox> MailboxesList = new List<Mailbox>();
void AddMailbox(Mailbox mailbox)
{
MailboxesList.Add(mailbox);
}
public IEnumerator<Mailbox> GetEnumerator() => MailboxesList.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => MailboxesList.GetEnumerator();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论