Example #1
0
 public AttributeParser(AttributeConfiguration configuration, IParameterFormatter parameterFormatter, IValueConverter valueConverter, IHelpPresenter helpPresenter)
 {
     Configuration     = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _attributeHandler = new AttributeHandler(configuration, parameterFormatter, (option, value) =>
     {
         var optionProperty = Configuration.GetOptionProperty(option);
         return(valueConverter.ConvertFromString(option, optionProperty.PropertyInfo, AttributeHandler.GetValueType(optionProperty.Option, optionProperty.PropertyInfo.PropertyType), value));
     },
                                              (option) =>
     {
         return(Configuration.GetOptionProperty(option).PropertyInfo.PropertyType);
     });
     _helpPresenter = helpPresenter ?? throw new ArgumentNullException(nameof(helpPresenter));
 }
            public void SetValue(object?value)
            {
                if (AttributeHandler.IsCollectionAttribute(Option))
                {
                    if (value == null)
                    {
                        throw new InvalidOperationException($"The target value for the property \"{ParameterInfo.Name}\" on \"{MethodName}\" is null, but it is marked as a collection.");
                    }

                    //TODO: Create element of the correct type.
                    if (Value == null)
                    {
                        var constructor = ParameterInfo.ParameterType.GetConstructors().FirstOrDefault((x) => x.IsPublic && x.GetParameters().Length == 0);
                        if (constructor != null)
                        {
                            Value = constructor.Invoke(new object[0]);
                        }
                        else
                        {
                            Value = Activator.CreateInstance(typeof(List <>).MakeGenericType(AttributeHandler.GetValueType(Option, ParameterInfo.ParameterType)));
                        }
                    }

                    var list = (IList)Value;

                    list.Clear();
                    foreach (var element in (IList)value)
                    {
                        list.Add(element);
                    }
                }
                else
                {
                    Value = value;
                }
            }