簡體   English   中英

為什么這段代碼會抱怨“泛型類型定義的arity”?

[英]Why would this code complain about “the arity of the generic type definition”?

我有一個通用類型:

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 )。

弄清楚了。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM