Question

In practice this seems simple but I'm getting really confused about it. Java's enumeration hasMoreElements() and nextElement() methods are related but work differently from C#'s IEnumerator MoveNext() and Current() properties of course. But how would I translate something like this?:

//class declaration, fields constructors, unrelated code etc.

private Vector atomlist = new Vector();

    public int getNumberBasis() {
    Enumeration basis = this.getBasisEnumeration();
    int numberBasis = 0;
    while (basis.hasMoreElements()) {
        Object temp = basis.nextElement();
        numberBasis++;
    }
    return numberBasis;
}


public Enumeration getBasisEnumeration() {
    return new BasisEnumeration(this);
}

    private class BasisEnumeration implements Enumeration {

    Enumeration atoms;

    Enumeration basis;

    public BasisEnumeration(Molecule molecule) {
        atoms = molecule.getAtomEnumeration();
        basis = ((Atom) atoms.nextElement()).getBasisEnumeration();
    }

    public boolean hasMoreElements() {
        return (atoms.hasMoreElements() || basis.hasMoreElements());
    }

    public Object nextElement() {
        if (basis.hasMoreElements())
            return basis.nextElement();
        else {
            basis = ((Atom) atoms.nextElement()).getBasisEnumeration();
            return basis.nextElement();
        }
    }

}

As you can see, the enumration class's methods are overloaded and I don't think replacing hasMoreElements and nextElement with MoveNext and Current everywhere would work... because the basis.nextElement() calls hasMoreElements() again in an if-else statement. If I was to replace hasMoreElements with MoveNext(), the code would advance twice instead of one.

Était-ce utile?

La solution

You can indeed implement IEnumerable yourself, but it generally needed only for exercises in internals of C#. You'd probably use either iterator method:

 IEnumerable<Atom> GetAtoms()
 {
    foreach(Atom item in basis)
    {
         yield return item;
    }
    foreach(Atom item in atoms)
    {
         yield return item;
    }
 }

Or Enumerable.Concat

 IEnumerable<Atom> GetAtoms()
 {
     return basis.Concat(atoms);
 }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top