0

これに問題があり、以下のコードに保存されているコレクションから特定の値を取得できない理由がよくわかりません...

public Dog Get(string name)
    {
        Dog dog = null;

        var context = HttpContext.Current;

        if (context.Cache[CacheKey] != null)
        {
            System.Collections.IDictionaryEnumerator en = context.Cache.GetEnumerator();

            while (en.MoveNext())
            {
                if (en.Key.ToString() == "AnimalStore")
                {
                    // I would like to use a foreach loop to look for a specific dog here but I get an error!
                    // foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
                    foreach (var item in en.Value)
                    {
                       // en.Value contains two Dog objects with data but I can't get at them or their properties....
                    }
                }

            }

            //dog = (Dog)context.Cache[CacheKey];
        }

        return dog;
    }

foreach ステートメントは、'System.Collections.IDictionaryEnumerator' に 'GetEnumerator' のパブリック定義が含まれていないため、'System.Collections.IDictionaryEnumerator' 型の変数を操作できません。

他の誰かが、配列をループして Dog.name を取得し、次のようなことを実行できない理由を説明できますか? //return dogs.Find(p => p.name == name); これは私にとって非常に紛らわしい概念なので、理解の助けに感謝します....

4

1 に答える 1

0

反復しようとしているオブジェクトがインターフェイスを実装していないため、このエラーが発生していIEnumerableます。

ここにオブジェクトがあるようen.Valueです(現在、テストするためのVSがありません)。その場合は、適切な型にキャストする必要があります。キャスト型がコレクションであり、インターフェイスを実装していない場合は、その場で拡張メソッドIEnumerableを呼び出す必要があります。そうでなければ、私が言ったように、適切な型にキャストする必要があります。AsEnumerable()System.Linq

于 2013-09-12T06:56:12.827 に答える