Пример #1
0
 private void loadTypeConverters()
 {
     writeDebug($"Found {TypeResolver.Count()} type resolvers.");
 }
Пример #2
0
        private object getTypedParameterValue(ParameterAttribute para, CommandLineParameterInfo pi)
        {
            if (para.Type == typeof(bool))
            {
                return(pi.Exists);
            }

            bool isList = typeof(IEnumerable).IsAssignableFrom(para.Type) && para.Type != typeof(string);

            if (pi.HasValue)
            {
                var value = pi.Value;

                if (para.Type.IsEnum)
                {
                    if (Enum.TryParse(para.Type, value, ignoreCase: true, out object res))
                    {
                        return(res);
                    }
                    else
                    {
                        throw new InvalidParameterException(para);
                    }
                }

                if (TypeResolver.IsResolvableType(para.Type))
                {
                    return(TypeResolver.Resolve(value, para.Type));
                }

                if (isList)
                {
                    var separator = " ";
                    if (!string.IsNullOrWhiteSpace(para.ListSeparator))
                    {
                        separator = para.ListSeparator;
                    }

                    var splitValue = value.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);

                    var underlyingType      = para.Type.GetGenericArguments().FirstOrDefault();
                    var constructedListType = typeof(List <>).MakeGenericType(underlyingType);
                    var constructedList     = (IList)Activator.CreateInstance(constructedListType);

                    try
                    {
                        if (Parameter.IsSimpleType(underlyingType))
                        {
                            splitValue.ToList().ForEach(x => constructedList.Add(Convert.ChangeType(x, underlyingType)));
                        }
                        else if (TypeResolver.IsResolvableType(underlyingType))
                        {
                            splitValue.ToList().ForEach(x => constructedList.Add(TypeResolver.Resolve(x, underlyingType)));
                        }
                    }
                    catch (FormatException)
                    {
                        throw new InvalidParameterException(para);
                    }

                    return(constructedList);
                }
                else
                {
                    return(Convert.ChangeType(value, para.Type));
                }
            }
            else
            {
                if (para.IsRequired)
                {
                    throw new ParameterMissingException(para);
                }
                else
                {
                    return(null);
                }
            }
        }