質問

私はについて質問があります IEnumerator.GetEnumerator() 方法。

public class NodeFull
{
    public enum Base : byte {A = 0, C, G, U };
    private int taxID;
    private List<int> children;

    public int TaxID
    {
        get { return taxID; }
        set { taxID = value; }
    }

    public int this[int i]
    {
        get { return children[i]; }
        set { children[i] = value; }
    }

    public IEnumerator GetEnumerator()
    {
        return (children as IEnumerator).GetEnumerator();
    }

    public TaxNodeFull(int taxID)
    {
        this.taxID = taxID;
        this.children = new List<int>(3);
    }
}

コンパイルしようとすると、エラーメッセージが表示されます

「System.Collections.IENUMERATOR」には「GetEnumerator」の定義は含まれておらず、拡張法はありません。「getEnumerator」getEnumerator 'type' system.collections.ienumerators 'の最初の引数を受け入れます(ディレクティブまたはアセンブリリファレンスを使用していない場合がありますか? ?)

コードに何か問題がありますか?

前もって感謝します


君たちありがとう。わかった。

役に立ちましたか?

解決

これは IEnumerable.GetEnumerator() (また IEnumerable<T>.GetEnumerator())、 いいえ IEnumerator.GetEnumerator(). 。メンバー IEnumerator それは MoveNext(), CurrentReset() (と Dispose 一般的なバージョン用)。 IEnumerable 「繰り返すことができるもの」(例:リスト)と IEnumerator データベースカーソルのように、その反復内の現在の状態を表します。

クラスが実装しないのは少し奇妙です IEnumerable また IEnumerable<T> 自体。私はこのようなものを期待しています:

class NodeFull : IEnumerable<int>
{
    ... other stuff as normal ...

    public IEnumerator<int> GetEnumerator()
    {
        return children.GetEnumerator();
    }

    // Use explicit interface implementation as there's a naming
    // clash. This is a standard pattern for implementing IEnumerable<T>.
    IEnumerator IEnumerable.GetEnumerator()
    {
        // Defer to generic version
        return GetEnumerator();
    }
}

他のヒント

子供たちです List<int>, 、それを実装します IEnumerable<int>IEnumerable. 。 GetEnumerator() メソッドは、これらのインターフェイスに対して定義されています IEnumerator.

children as IEnumerator nullになるはずです。

ありません GetEnumerator() の方法 IENUMERATOR インターフェース。使用しようとしていますか IENUMERABLE おそらくインターフェイス?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top