dka*_*man 12 c# generics reflection arity
我有一个通用类型:
class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
Run Code Online (Sandbox Code Playgroud)
还有一个工厂方法,它将(应该)为给定的字典类型创建此类的实例.
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);
}
Run Code Online (Sandbox Code Playgroud)
剥去所有无关紧要的东西 - 即使这段代码也会引发同样的异常.
private static object CreateDictionaryComparer()
{
Type def = typeof(DictionaryComparer<,>);
Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) });
return Activator.CreateInstance(t);
}
Run Code Online (Sandbox Code Playgroud)
Asserts传递所以我知道它T是通用的并且有两个通用参数.MakeGenericType然而,除了以下内容的线路:
提供的泛型参数的数量不等于泛型类型定义的arity.
参数名称:实例化
我过去做过这种事情,因为我的生活无法弄清楚为什么在这种情况下这不起作用.(加上我必须谷歌arity).
dka*_*man 15
弄清楚了.
我曾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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8244 次 |
| 最近记录: |