简体   繁体   中英

Implementing IEnumerable interface to my class

I have this class, wherein I want to implement IEnumerable to be able to use 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.

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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