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

问题描述 投票:12回答:2

我有一个通用类型:

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。

参数名称:实例化

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

c# generics reflection arity
2个回答
14
投票

弄清楚了。

我把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
投票

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) });
© www.soinside.com 2019 - 2024. All rights reserved.