public static object Convert(object value, Type targetType, ITypeCache typeCache = null) { if (typeCache == null) { typeCache = TypeCaches.TypeCache("global"); } if (value == null && !typeCache.IsValue(targetType)) { return(null); } else if (TryConvert(value, targetType, typeCache, out var result)) { return(result); } throw new FormatException($"Unable to convert value from type {value.GetType()} to type {targetType}"); }
private EdmMetadataCache CreateMdc(string key, string metadata) { return(new EdmMetadataCache(key, metadata, TypeCaches.TypeCache(key))); }
private EdmMetadataCache CreateMdc(string key, string metadata) { return(new EdmMetadataCache(key, metadata, TypeCaches.TypeCache(key, Settings.NameMatchResolver))); }
public static bool TryConvert(object value, Type targetType, ITypeCache typeCache, out object result) { if (typeCache == null) { typeCache = TypeCaches.TypeCache("global"); } try { if (value == null) { if (typeCache.IsValue(targetType)) { result = Activator.CreateInstance(targetType); } else { result = null; } } else if (typeCache.IsTypeAssignableFrom(targetType, value.GetType())) { result = value; } else if (targetType == typeof(string)) { result = value.ToString(); } else if (typeCache.IsEnumType(targetType) && value is string) { result = Enum.Parse(targetType, value.ToString(), true); } else if (targetType == typeof(byte[]) && value is string) { result = System.Convert.FromBase64String(value.ToString()); } else if (targetType == typeof(string) && value is byte[]) { result = System.Convert.ToBase64String((byte[])value); } else if ((targetType == typeof(DateTime) || targetType == typeof(DateTime?)) && value is DateTimeOffset offset) { result = offset.DateTime; } else if ((targetType == typeof(DateTimeOffset) || targetType == typeof(DateTimeOffset?)) && value is DateTime time) { result = new DateTimeOffset(time); } else if (typeCache.IsEnumType(targetType)) { result = Enum.ToObject(targetType, value); } else if (targetType == typeof(Guid) && value is string) { result = new Guid(value.ToString()); } else if (Nullable.GetUnderlyingType(targetType) != null) { result = Convert(value, Nullable.GetUnderlyingType(targetType), typeCache); } else { result = System.Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); } return(true); } catch (Exception) { result = null; return(false); } }