private static object ConvertSingle(Type type, ITypeCache typeCache, object itemValue) { object TryConvert(object v, Type t) => typeCache.TryConvert(v, t, out var result) ? result : v; return(type == typeof(ODataEntryAnnotations) ? itemValue : IsCompoundType(type, typeCache) ? itemValue.ToDictionary(typeCache).ToObject(typeCache, type) : type.IsEnumType() ? ConvertEnum(type, typeCache, itemValue) : TryConvert(itemValue, type)); }
public static object Convert(this ITypeCache typeCache, object value, Type targetType) { if (value == null && !typeCache.IsValue(targetType)) { return(null); } else if (typeCache.TryConvert(value, targetType, out var result)) { return(result); } throw new FormatException($"Unable to convert value from type {value.GetType()} to type {targetType}"); }
private static object ConvertEnum(Type type, ITypeCache typeCache, object itemValue) { if (itemValue == null) { return(null); } var stringValue = itemValue.ToString(); if (int.TryParse(stringValue, out var intValue)) { typeCache.TryConvert(intValue, type, out var result); return(result); } else { return(Enum.Parse(type, stringValue, false)); } }