16

私はジェネリック型を持っています:

class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>

そして、与えられたディクショナリタイプに対してこのクラスのインスタンスを作成する(すべき)ファクトリメソッド。

    private static IEqualityComparer<T> CreateDictionaryComparer<T>()
    {
        Type def = typeof(DictionaryComparer<,>);
        Debug.Assert(typeof(T).IsGenericType);
        Debug.Assert(typeof(T).GetGenericArguments().Length == 2);

        Type t = def.MakeGenericType(typeof(T).GetGenericArguments());

        return (IEqualityComparer<T>)Activator.CreateInstance(t);
    }

無関係なものをすべて取り除きます-このコードでさえ同じ例外をスローします。

private static object CreateDictionaryComparer()
{
    Type def = typeof(DictionaryComparer<,>);

    Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });

    return Activator.CreateInstance(t);
}

アサートはパスするので、それTは一般的であり、2つの一般的な引数があることがわかります。MakeGenericTypeただし、次の行は次の場合を除きます。

提供されるジェネリック引数の数は、ジェネリック型定義のアリティと同じではありません。

パラメータ名:インスタンス化

私は過去にこの種のことをしたことがありますが、この場合、なぜこれが機能しないのか理解できません。(さらに、私はグーグルのアリティにならなければなりませんでした)。

4

2 に答える 2

18

理解した。

私はDictionaryComparerインナークラスとして宣言しました。MakeGenericTypeを作りたかったのに提供されなかったとしかQuery<T>.DictionaryComparer<string,object>思えませんT

失敗したコード

class Program
{
    static void Main(string[] args)
    {
        var q = new Query<int>();
        q.CreateError();
    }
}

public class Query<TSource>
{
    public Query()
    {    
    }

    public object CreateError()
    {
        Type def = typeof(DictionaryComparer<,>);

        Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });

        return Activator.CreateInstance(t);
    }

    class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
    {
        public DictionaryComparer()
        {
        }

        public bool Equals(IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y)
        {
            if (x.Count != y.Count)
                return false;

            return GetHashCode(x) == GetHashCode(y);
        }

        public int GetHashCode(IDictionary<TKey, TValue> obj)
        {
            int hash = 0;
            unchecked
            {
                foreach (KeyValuePair<TKey, TValue> pair in obj)
                {
                    int key = pair.Key.GetHashCode();
                    int value = pair.Value != null ? pair.Value.GetHashCode() : 0;
                    hash ^= key ^ value;
                }
            }
            return hash;
        }
    }
}
于 2010-09-22T03:12:36.547 に答える
1

CLRは、アプリケーションで使用されているすべての型の内部データ構造を作成します。これらのデータ構造は、型オブジェクトと呼ばれます。ジェネリック型パラメーターを持つ型はオープン型と呼ばれ、CLRはオープン型のインスタンスを構築することを許可しません(CLRがインターフェイス型のインスタンスの構築を防ぐ方法と同様です)。

変化する

Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });

Type t = def.MakeGenericType(new Type[] { typeof(TSource), typeof(String), typeof(object) });
于 2015-01-22T10:05:27.180 に答える