【发布时间】:2010-09-22 02:46:51
【问题描述】:
我有一个泛型类型:
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 是通用的并且有两个通用参数。带有MakeGenericType 的行但是除了:
提供的泛型参数的数量不等于泛型类型定义的数量。
参数名称:实例化
我过去做过这种事情,我一生都无法弄清楚为什么这在这种情况下不起作用。 (另外我不得不谷歌arity)。
【问题讨论】:
-
您将
T传递给CreateDictionaryComparer的内容是什么?我已经尝试通过CreateDictionaryComparer<IDictionary<string, string>>(),这对我来说很好(使用 Mono C# 编译器版本 1.9.1.0)。 -
我有 DictionaryComparer 作为一个内部类,它本身就是通用的。认为这是在冲洗作品。
-
出于好奇,您能否提供完整的(失败的)示例,以便我在编译器上进行尝试?
-
谢谢!我很感激。
标签: c# generics reflection arity