简体   繁体   English

在我的类中实现IEnumerable接口

[英]Implementing IEnumerable interface to my class

I have this class, wherein I want to implement IEnumerable to be able to use foreach(). 我有这个类,其中我想实现IEnumerable以便能够使用foreach()。 Here is my code by i think i'm not doing it correctly 这是我的代码,我想我没有正确地做到这一点

public class SearchResult : IEnumerable<SearchResult>
{

    string Name { get; set; }
    int Rating { get; set; }

    public IEnumerator<SearchResult> GetEnumerator()
    {
        return( this );
    }
}

You could do: 你可以这样做:

public IEnumerator<SearchResult> GetEnumerator()
{
    yield return this;
}

However it's unusual for an object like this to implement IEnumerable<T> and return itself in a single-element sequence. 然而,像这样的对象实现IEnumerable<T>并以单元素序列返回自身是不寻常的。

You might want to create a utility method instead: 您可能想要创建一个实用工具方法:

public static IEnumerable<T> ToSequence<T>(T instance)
{
    reutrn new[] { instance };
}

If you really truly swear that you need to do this: 如果你真的发誓你需要这样做:

SearchResult justOne = ... blah ...;
foreach (SearchResult eachOne in justOne) {
   ... blah ...
}

Then you could do this minor modification to your method (use yield return instead of return): 然后你可以对你的方法进行这个小修改(使用yield return而不是return):

public IEnumerator<SearchResult> GetEnumerator()
{
    yield return( this );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM