How to enforce required command-line options with NDesk.Options?

前端 未结 2 1358
青春惊慌失措
青春惊慌失措 2020-12-09 01:33

I was just writing a console utility and decided to use NDesk.Options for command-line parsing. My question is, How do I enforce required command-line options?

I se

2条回答
  •  时光说笑
    2020-12-09 02:10

    One can extend NDesk.Options a little bit to add this functionality.

    First, create a SetupOption class that would implement INotifyPropertyChanged:

    class SetupOption : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        #endregion
    
        private T _value;
    
        public T Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(_value, new PropertyChangedEventArgs("Value"));
                }
            }
        }
    }
    

    Second, add an overload to ActionOption that takes an instance of INotifyPropertyChanged as an argument (call it targetValue).

    Third, modify the Option class to add private INotifyPropertyChanged targetValue and private bool optionSet.

    Fourth, pass the targetValue to the Option when creating it. Subscribe to the PropertyChanged event. In it, set "optionSet" to true if the sender is not null.

    Add a Validate() method to the Option class that would throw an exception if targetValue is not null and optionSet is false.

    Finally, add a Validate() method to the OptionContext that would loop over all options and call their respective Validate() methods. Call it at the very end of the Parse() method.

    Here is the zip of the modified code: http://www.davidair.com/misc/options.zip

提交回复
热议问题