Beispiel #1
0
        private static object ConvertToVar(object value, Type targetType)
        {
            Type sourceType = value?.GetType();

            if (value is Var var)
            {
                value      = var.RawValue;
                sourceType = value?.GetType();
            }

            object convertedValue = null;

            if (Is.Collection(value))
            {
                var elementType = TypeOf.Var(targetType);
                var arrayType   = elementType.MakeArrayType();
                convertedValue = ConvertValue(value, arrayType);
            }
            else if (value is Range range)
            {
                convertedValue = range;
            }
            else
            {
                var elementType = TypeOf.Var(targetType);
                convertedValue = ConvertValue(value, elementType);
            }

            var varInstance = (Var)Activator.CreateInstance(targetType);

            varInstance.RawValue = convertedValue;
            return(varInstance);
        }
Beispiel #2
0
        private static object Convert(object value, Type targetType, object defaultValue)
        {
            if (defaultValue == null)
            {
                defaultValue = Default.Of(targetType);
            }

            if (value == null || value == DBNull.Value)
            {
                return(defaultValue);
            }

            if (value is IChangeTypeSupport support)
            {
                var done = support.ChangeTo(targetType, out object target);
                if (done)
                {
                    return(target);
                }
            }

            if (Is.Collection(targetType))
            {
                var elementType = TypeOf.CollectionElement(targetType);
                if (targetType.IsArray)
                {
                    var sourceList = value as IList ?? new[] { value };
                    var targetList = (IList)Activator.CreateInstance(targetType, sourceList.Count);
                    for (int i = 0; i < sourceList.Count; i++)
                    {
                        targetList[i] = ConvertItem(sourceList[i], elementType);
                    }
                    return(targetList);
                }
                else
                {
                    var sourceList = value as IList ?? new[] { value };
                    var targetList = (IList)Activator.CreateInstance(targetType);
                    foreach (var sourceElement in sourceList)
                    {
                        var targetElement = ConvertItem(sourceElement, elementType);
                        targetList.Add(targetElement);
                    }
                    return(targetList);
                }
            }
            else
            {
                return(ConvertItem(value, targetType) ?? defaultValue);
            }
        }