为什么这段代码会抱怨“泛型类型定义的arity”?

时间:2010-09-22 02:46:52

标签: c# generics reflection arity

我有一个通用类型:

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);
}

Asserts通过,所以我知道T是通用的并且有两个通用参数。 MakeGenericType行除了以下内容之外:

  

提供的泛型参数的数量不等于泛型类型定义的arity。

     

参数名称:instantiation

我过去做过这种事,因为我的生活无法弄清楚为什么在这种情况下这不起作用。 (加上我必须使用Google arity)。

2 个答案:

答案 0 :(得分:13)

想出来。

我将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;
        }
    }
}

答案 1 :(得分: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) });