枚举类型数组的命令行分析器



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

 [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;
    }

不确定这是否是您要找的,如果是这样,它应该会让您走上正确的轨道。

public enum OptimizeFor
{
    Unspecified,
    Speed,
    Accuracy
}
public class EnumParser
{
    public static IEnumerable<TEnum> FindSelected<TEnum>(IEnumerable<string> enumItemNames)
    {
        var selectedOtions = Enum.GetNames(typeof(TEnum))
            .Intersect(enumItemNames, StringComparer.InvariantCultureIgnoreCase)
            .Select(i => Enum.Parse(typeof(TEnum), i))
            .Cast<TEnum>();
        return selectedOtions;
    }
}
class Program
{
    static void Main(string[] args)
    {
        //Some fake arguments
        args = new[] {"-o", "SPEED", "accuracy", "SomethingElse"};
        var selectedEnumVals = EnumParser.FindSelected<OptimizeFor>(args);
        selectedEnumVals.Select(i => i.ToString()).ToList().ForEach(Console.WriteLine);
        Console.Read();
    }
}

最新更新