C#中如何创建SortedDictionary`2+ValueCollection类型对象
问题背景
- 待匹配目标类型:
System.Collections.Generic.SortedDictionary2+ValueCollection` - 测试现象:执行
Console.WriteLine(typeof(SortedDictionary<string, object>));时,输出类型为System.Collections.Generic.SortedDictionary2`,和目标类型不匹配 - 核心诉求:找到正确的类型获取/对象创建方式,满足判定条件
typeof(TheType) == System.Collections.Generic.SortedDictionary2+ValueCollection`
原因解释
CLR类型名中+代表嵌套类型,SortedDictionary2+ValueCollection是定义在SortedDictionary<TKey,TValue>泛型类内部的嵌套类,和外层的SortedDictionary<TKey,TValue>本身是完全不同的两个类型,直接取外层类的typeof`自然无法匹配。
实现方案
1. 静态获取目标类型(已知泛型参数场景)
如果已经确定SortedDictionary的键、值泛型参数,可以直接通过嵌套类型访问语法获取对应Type对象:
// 以键为string、值为object的场景为例 Type targetType = typeof(SortedDictionary<string, object>.ValueCollection); // 验证类型FullName,会输出带+标记的目标类型名 Console.WriteLine(targetType.FullName);
2. 反射动态获取目标类型(未知泛型参数场景)
如果需要动态构造不同泛型参数的目标类型,可以通过反射获取嵌套类型后再构造闭合泛型:
using System.Reflection; // 先获取开放泛型的SortedDictionary<,>类型 Type openDictType = typeof(SortedDictionary<,>); // 从开放泛型类型上获取嵌套的ValueCollection开放类型 Type openValueCollType = openDictType.GetNestedType("ValueCollection", BindingFlags.Public); // 传入需要的泛型参数(此处以string、object为例),构造闭合的目标类型 Type closedTargetType = openValueCollType.MakeGenericType(typeof(string), typeof(object));
3. 创建目标类型的实例
ValueCollection没有公开的无参构造函数,它的实例必须依附于一个对应的SortedDictionary实例,最简单的获取实例方式是通过字典的Values属性:
// 先创建对应泛型参数的SortedDictionary实例 SortedDictionary<string, object> testDict = new SortedDictionary<string, object>(); // 获取的Values属性就是目标ValueCollection类型的实例 var valueCollInstance = testDict.Values; // 验证实例类型,判定结果为true bool instanceTypeMatch = valueCollInstance.GetType() == typeof(SortedDictionary<string, object>.ValueCollection);
注意事项
- 直接调用
Type.GetType("System.Collections.Generic.SortedDictionary2+ValueCollection")`拿到的是未指定泛型参数的开放泛型嵌套类型,和填充了具体键值类型的闭合泛型类型不相等,做相等判定时必须保证泛型参数完全对应。 - 不建议直接通过反射调用构造函数生成
ValueCollection实例,这个类型的设计就是依附于父SortedDictionary存在,脱离父字典创建的实例没有实际使用价值,大概率会触发运行时错误。
内容的提问来源于stack exchange,提问作者DinDan
相关产品推荐
相关产品推荐

