2

問題

using System.Collections.Generic;
using System.Linq;

基本クラスと2つの派生クラスがある場合:

class Base{}
class Derived0 : Base{}
class Derived1 : Base{}

私は2つのタイプの辞書を持っています:

IDictionary<String, Derived0> d0 = ...;
IDictionary<String, Derived1> d1 = ...;

タイプが必要な2つの辞書の和集合を見つけたいと思いますIDictionary<String, Base>。(キーは両方の辞書で一意であることをすでに知っているので、重複がある場合の動作は気にしません。)


試み

それらが同じタイプであれば、私は使用できます

var union = d0.Concat(d1);

しかし、これによりエラーが発生します(を使用してコンパイルdmcs):

Test.cs(15,20): error CS0411: The type arguments for method `System.Linq.Queryable.Concat<TSource>(this System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

Base型引数として明示的に指定した場合:

IDictionary<string, Base> union = d0.Concat<Base>(d1);

それでも機能しません:

Test.cs(15,42): error CS1928: Type `System.Collections.Generic.IDictionary<string,Derived0>' does not contain a member `Concat' and the best extension method overload `System.Linq.Enumerable.Concat<Base>(this System.Collections.Generic.IEnumerable<Base>, System.Collections.Generic.IEnumerable<Base>)' has some invalid arguments
/usr/lib/mono/gac/System.Core/4.0.0.0__b77a5c561934e089/System.Core.dll (Location of the symbol related to previous error)
Test.cs(15,42): error CS1929: Extension method instance type `System.Collections.Generic.IDictionary<string,Derived0>' cannot be converted to `System.Collections.Generic.IEnumerable<Base>'

原則として、新しい辞書オブジェクトを作成しているので、ここでは分散は重要ではありませんが、型システムでそれを表現する方法を理解することはできません。

4

2 に答える 2

0

次の拡張メソッドを使用できます。

    class Base { }
    class Derived0 : Base { }
    class Derived1 : Base { }

    class Program {
        static void Main(string[] args) {
            var d0 = new Dictionary<string, Derived0>();
            var d1 = new Dictionary<string, Derived1>();
            var b = d0.Merge<string, Derived0, Derived1, Base>(d1);
        }
    }

    public static class DictionaryExtensions {
        public static Dictionary<TKey, TBase> Merge<TKey, TValue1, TValue2, TBase>(this IDictionary<TKey, TValue1> thisDictionary, IDictionary<TKey, TValue2> thatDictionary)
            where TValue1 : TBase
            where TValue2 : TBase {
            var resultDictionary = new Dictionary<TKey, TBase>();
            resultDictionary.AddRange(thisDictionary);
            resultDictionary.AddRange(thatDictionary);

            return resultDictionary;
        }

        public static void AddRange<TKey, TBase, TValue>(this IDictionary<TKey, TBase> dictionary, IDictionary<TKey, TValue> dictionaryToAdd) where TValue : TBase {
            foreach (var kvp in dictionaryToAdd) {
                dictionary.Add(kvp.Key, kvp.Value);
            }
        }
    }
于 2012-11-21T07:07:22.897 に答える