Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c# - How do I implement IEnumerable?

I have a class that contains a static number of objects. This class needs to be frequently 'compared' to other classes that will be simple List objects.

public partial class Sheet
{
 public Item X{ get; set; }
 public Item Y{ get; set; }
 public Item Z{ get; set; }
}

the items are obviously not going to be "X" "Y" "Z", those are just generic names for example. The problem is that due to the nature of what needs to be done, a List won't work; even though everything in here is going to be of type Item. It is like a checklist of very specific things that has to be tested against in both code and runtime.

This works all fine and well; it isn't my issue. My issue is iterating it. For instance I want to do the following...

List<Item> UncheckedItems = // Repository Logic Here.

UncheckedItems contains all available items; and the CheckedItems is the Sheet class instance. CheckedItems will contain items that were moved from Unchecked to Checked; however due to the nature of the storage system, items moved to Checked CANNOT be REMOVED from Unchecked. I simply want to iterate through "Checked" and remove anything from the list in Unchecked that is already in "Checked".

So naturally, that would go like this with a normal list.

foreach(Item item in Unchecked)
{
 if( Checked.Contains(item) )
 Unchecked.Remove( item );
}

But since "Sheet" is not a 'List', I cannot do that. So I wanted to implement IEnumerable so that I could. Any suggestions? I've never implemented IEnumerable directly before and I'm pretty confused as to where to begin.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to create an iterator that returns the Items that reside in the Sheet.

Using Iterators

public partial class Sheet
{
    public Item X{ get; set; }
    public Item Y{ get; set; }
    public Item Z{ get; set; }

    public IEnumerable<Item> EnumerateItems()
    {
        yield return X;
        yield return Y;
        yield return Z;
        // ...
    }
}

If you don't want to have to call the method you can do this.

public partial class Sheet : IEnumerable<Item>
{
    public Item X{ get; set; }
    public Item Y{ get; set; }
    public Item Z{ get; set; }

    public IEnumerator<Item> GetEnumerator()
    {
        yield return X;
        yield return Y;
        yield return Z;
        // ...
    }

    IEnumerator IEnumerator.GetEnumerator()
    {
        return GetEnumerator();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...