diff --git a/Cast.cs b/Cast.cs index 815c329..6090ef6 100644 --- a/Cast.cs +++ b/Cast.cs @@ -11,6 +11,8 @@ using System; using System.Reflection; using System.Linq; using System.Threading; +using System.Net.Http.Headers; + namespace ln.type { public static class Cast @@ -18,26 +20,34 @@ namespace ln.type public static T To(object value) => (T)To(value, typeof(T)); public static object To(object value, Type targetType) { + if (!To(value, targetType, out object targetValue)) + throw new NotSupportedException(); + return targetValue; + } + public static bool To(object value, Type targetType, out object targetValue) + { + targetValue = null; if (Object.ReferenceEquals(null, value)) - return null; + return true; if (targetType.IsInstanceOfType(value)) - return value; - - object casted; + { + targetValue = value; + return true; + } if ( - !Implicit(value, targetType, out casted) && - !Implicit(value, value.GetType(), targetType, out casted) && - !Explicit(value, targetType, out casted) && - !Explicit(value, value.GetType(), targetType, out casted) + !Implicit(value, targetType, out targetValue) && + !Implicit(value, value.GetType(), targetType, out targetValue) && + !Explicit(value, targetType, out targetValue) && + !Explicit(value, value.GetType(), targetType, out targetValue) ) { if (targetType.IsEnum) { if (value is string sValue) { - casted = Enum.Parse(targetType, sValue); + targetValue = Enum.Parse(targetType, sValue); } else { throw new NotSupportedException(); @@ -49,16 +59,21 @@ namespace ln.type Array castedArray = Array.CreateInstance(targetType.GetElementType(), array.Length); for (int n = 0; n < array.Length; n++) - castedArray.SetValue(To(array.GetValue(n), targetType.GetElementType()), n); + { + if (!To(array.GetValue(n), targetType.GetElementType(), out object el)) + return false; - casted = castedArray; + castedArray.SetValue(el, n); + } + + targetValue = castedArray; } else { - casted = Convert.ChangeType(value, targetType); + targetValue = Convert.ChangeType(value, targetType); } } - return casted; + return true; } public static bool Implicit(object value, Type type, out object casted) => Implicit(value, type, type, out casted); diff --git a/ln.type.csproj b/ln.type.csproj index aae4aac..2a7a30e 100644 --- a/ln.type.csproj +++ b/ln.type.csproj @@ -3,7 +3,7 @@ netcoreapp3.1 true - 0.1.2 + 0.1.3 Harald Wolff-Thobaben l--n.de 0.0.1.0