我们试图找到一个可以解析带有枚举的数组的命令行解析器。
CommandlineParser支持使用int或string解析数组,但不支持枚举。
例如

 [OptionArray("o", "output", HelpText = "The output files to generate.", DefaultValue = new[] { "OptimizeFor.Accuracy", "OptimizeFor.Speed" })]
  public string[] OutputFiles { get; set; }


工作正常。但不是以下之一:

 public enum OptimizeFor
        {
            Unspecified,
            Speed,
            Accuracy
        }
    [OptionArray("o", "output", HelpText = "The output files to generate.", DefaultValue = new[] { OptimizeFor.Accuracy, OptimizeFor.Speed })]
    public OptimizeFor[] OutputFiles { get; set; }

最佳答案

这是命令行的修补程序,用于解析枚举数组。我创建了一个拉取请求。 https://github.com/gsscoder/commandline/pull/148

    public bool SetValue(IList<string> values, object options)
    {
        var elementType = _property.PropertyType.GetElementType();

        var propertyType = elementType;
        if (propertyType.IsGenericType &&
        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            propertyType = propertyType.GetGenericArguments()[0];
        }

        var array = Array.CreateInstance(elementType, values.Count);

        for (var i = 0; i < array.Length; i++)
        {
            try
            {
                if (propertyType.BaseType.Equals(typeof (System.Enum)))
                {
                    array.SetValue(Enum.Parse(propertyType, values[i]), i);
                    _property.SetValue(options, array, null);
                }
                else
                {
                    array.SetValue(Convert.ChangeType(values[i], elementType, _parsingCulture), i);
                    _property.SetValue(options, array, null);
                }
            }
            catch (FormatException)
            {
                return false;
            }
        }

        return ReceivedValue = true;
    }

10-02 01:45
查看更多