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
296 views
in Technique[技术] by (71.8m points)

c# - How do I make a class iterable?

This is my class

public class csWordSimilarity
{
    public int irColumn1 = 0;
    public int irColumn2 = 0;
    public int irColumn3 = 0;
    public int irColumn4 = 0;
    public int irColumn5 = 0;
}

I want to make that class iterable to be used like the way below

foreach (int irVal in myVarWordSimilarity)
{

} 

myVarWordSimilarity is csWordSimilarity type. So I want to iterate all public int variables. How do I need to modify csWordSimilarity class for making it iterable like the way above.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can implement IEnumerable and have the GetEnumerator override return an "iterator" over the variables using the yield statement

class csWordSimilarity : IEnumerable<int>
{
    private int _var1 = 1;
    private int _var2 = 1;
    private int _var3 = 1;
    private int _var4 = 1;

    public IEnumerator<int> GetEnumerator()
    {
        yield return _var1;
        yield return _var2;
        yield return _var3;
        yield return _var4;
    }

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

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

...