C#将系统Dictionary转换为Configurator自定义类型解决返回值报错问题
问题根因
报错
Use Configurator Types instead of System.Type System.Collections.Generic.Dictionary2[System.String,System.Int32]的原因是你直接将.NET 原生Dictionary类型传入Value构造函数,Configurator 宿主仅识别自身定义的集合类型IExpressionValueCollection`,不支持系统内置集合类型。
解决方法
不需要额外配置,只需将原生Dictionary转换为Configurator的IExpressionValueCollection类型再返回即可,修改后的代码如下:
// 原有字典定义逻辑不变 Dictionary<string, int> stockLengths = new Dictionary<string, int>(); stockLengths.Add("Length_5000", 0); stockLengths.Add("Length_3000", 0); // 新增转换逻辑:构造Configurator识别的集合实例 Value collectionContainer = new Value(DataType.Collection); IExpressionValueCollection targetCollection = collectionContainer.AsCollection(); // 遍历原生字典写入自定义集合 foreach (var item in stockLengths) { // 按key创建对应数值类型的集合元素 var collectionElement = targetCollection.GetOrCreateElement(item.Key, DataType.Number); // Configurator的数值类型为decimal,需做类型转换 collectionElement.Value = (decimal)item.Value; } // 用转换后的自定义集合构造返回值 Value result = new Value(targetCollection); return result;
核心说明
Value结构体内置了接收IExpressionValueCollection参数的构造函数,传入转换后的集合实例即可被宿主正常识别- 所有字典的值需要和
DataType枚举定义匹配:数字类型转decimal对应DataType.Number、布尔值对应DataType.Boolean、字符串对应DataType.String - 无需额外引用或配置,转换逻辑即可兼容宿主的类型校验规则
内容的提问来源于stack exchange,提问作者mhk
相关产品推荐
相关产品推荐

