You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OptionBase.cs 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. namespace OptionParser {
  10. public abstract class OptionBase {
  11. public OptionBase(string[] arguments)
  12. {
  13. Parse(arguments);
  14. }
  15. public void Parse(string[] arguments) {
  16. List<string> argList = arguments.ToList<string>();
  17. FieldInfo[] fields = GetType().GetFields();
  18. foreach (var f in fields) {
  19. if (f.IsDefined(typeof(OptionParserAttribute), false)) {
  20. var attributes = (OptionParserAttribute[])f.GetCustomAttributes(typeof(OptionParserAttribute), false);
  21. foreach (var attribute in attributes) {
  22. if (attribute.Default != null) {
  23. f.SetValue(this, attribute.Default);
  24. }
  25. bool optionSet = false;
  26. for (int i = 0; i < argList.Count; i++) {
  27. if (argList[i].IsOptionFor(attribute.Name, attribute.Switch)) {
  28. int range = 2;
  29. object val = null;
  30. if (argList.Count > 1)
  31. {
  32. val = argList[i + 1];
  33. }
  34. if (attribute.OptionType == typeof(bool))
  35. {
  36. range = 1;
  37. val = !Convert.ToBoolean(f.GetValue(this));
  38. }
  39. f.SetValue(this, val);
  40. argList.RemoveRange(i, range);
  41. optionSet = true;
  42. break;
  43. }
  44. }
  45. var desc =
  46. (f.GetCustomAttributes(typeof (DescriptionAttribute), false).First() as DescriptionAttribute).Description;
  47. if (attribute.Required && !optionSet)
  48. {
  49. throw new OptionRequiredException(message: string.Format("Option '{0}' is required.", attribute.Name),
  50. option: attribute.Name,
  51. description: desc
  52. );
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }