コード例 #1
0
        private static IDictionary TryConvertDictionary(IDictionary value, ColumnDesc column, Type targetType)
        {
            if (targetType.GetTypeInfo().IsInstanceOfType(value))
            {
                return(value);
            }
            var  mapColumnInfo = (MapColumnInfo)column.TypeInfo;
            Type childTargetKeyType;
            Type childTargetValueType;

            if (!Utils.IsIDictionary(targetType, out childTargetKeyType, out childTargetValueType))
            {
                throw new InvalidCastException(string.Format("Unable to cast object of type '{0}' to type '{1}'",
                                                             value.GetType(), targetType));
            }
            var childTypes = value.GetType().GetTypeInfo().GetGenericArguments();

            if (!childTargetKeyType.GetTypeInfo().IsAssignableFrom(childTypes[0]) ||
                !childTargetValueType.GetTypeInfo().IsAssignableFrom(childTypes[1]))
            {
                // Convert to target type
                var type   = typeof(SortedDictionary <,>).MakeGenericType(childTargetKeyType, childTargetValueType);
                var result = (IDictionary)Activator.CreateInstance(type);
                foreach (DictionaryEntry entry in value)
                {
                    result.Add(
                        TryConvertToType(entry.Key, new ColumnDesc
                    {
                        TypeCode = mapColumnInfo.KeyTypeCode,
                        TypeInfo = mapColumnInfo.KeyTypeInfo
                    }, childTargetKeyType),
                        TryConvertToType(entry.Value, new ColumnDesc
                    {
                        TypeCode = mapColumnInfo.ValueTypeCode,
                        TypeInfo = mapColumnInfo.ValueTypeInfo
                    }, childTargetValueType));
                }
                return(result);
            }
            return(value);
        }