0

ジェネリック ValueCollection を ICollection として返そうとしています。彼の MSDN ドキュメントから、Dictionary.ValueCollection は ICollection インターフェイスを実装していると書かれています。ただし、何らかの理由で、ValueCollection を ICollection としてキャストする必要があるときにエラーが発生します。これはコード サンプルで、その下に表示されるエラーが表示されます。

public ICollection<T> GetAllComponents<T>() where T : Component
    {
        Dictionary<Entity, Component>.ValueCollection retval = null;

        if(!this.componentEntityDatabase.ContainsKey(typeof(T)))
        {
            Logger.w (Logger.GetSimpleTagForCurrentMethod (this), "Could not find Component " + typeof(T).Name + " in database");
            return new List<T>();
        }

        Dictionary<Entity, Component> entityRegistry = this.componentEntityDatabase [typeof(T)];

        retval = entityRegistry.Values;

        return (ICollection<T>)retval;

    }

エラー:

Cannot convert type 'Systems.Collections.Generic.Dictionary<Entity,Component>.ValueCollection' to System.Collections.Generic.ICollection<T>

私はこれを間違っていますか?または、ディクショナリから値をコピーせずにこれを達成する別の方法はありますか?

4

1 に答える 1

0

この場合、ではなくをValueCollection実装します。である必要がありますが、すべての値が型になるとは限りません。ICollection<Component>ICollection<T>TComponentT

以下にいくつかの選択肢を示します。

  • 戻り値の型を次のように変更しますICollection<Component>
  • から返されたディクショナリ内のすべての値componentEntityDatabaseが 型Tである場合は、に変更entityRegistryしますDictionary<Entity, T>

  • 型の値のみOfTypeを返すために使用します。T

    retval = entityRegistry.Values.OfType<T>().ToList();  // turn into a List to get back to `ICollection<T>`  
    

編集

さらに詳しく見てみると、結果を type のオブジェクトだけに制限する必要がありますT。を使用するOfTypeのがおそらく最も安全な方法です。

于 2013-08-21T01:01:49.760 に答える