[Mono-dev] Program Option Parsing Library

Jay Logue jay-MonoDev at toaster.com
Fri Jan 11 17:06:13 EST 2008


Jonathan Pryor wrote:
> (aside from syntax and tests) Options _should_ currently be .NET 2.0 compatible
>   
I think 2.0 compatibility is important.  Not everybody is ready to jump 
on the C# 3.0 bandwagon (my company included).
> I guess I should create a new delegate type:
>
> 	delegate string OptionLocalizer (string format, string[] args);
>
> Other possible type names appreciated (and I don't like Rafael's
> TranslateIt name. ;-)
>   
I like this approach.  Would it be used for option descriptions as well? 
> This is also a good idea, and suffers the same problem as providing the
> actual option used: the callback doesn't have that information, and thus
> can't provide it in the OptionException.
>   
I faced this exact issue in a configuration system I wrote, except there 
the problem was exacerbated by the need to have file and line 
information in the exception (plus it was based on .NET 1.1, so no anon 
delegates to make things prettier). I  solved it by requiring the use of 
a context object.

How about this.  Create a delegate that takes the necessary context 
information, e.g.:

    delegate void OptionAction<T>(T v, string optionName);

and use this as the argument to the workhorse Add<T> method:

    public Options Add<T> (string options, string description, 
OptionAction<T> action)

then create an overloaded Add<T> that accepts an Action<T> and calls the 
workhorse method:

    public Options Add<T>(string options, string description, Action<T> 
action)
    {
        return Add(options, description, delegate(T v, string 
optionName) { action(v); });
    }

That way the user can make use of the context when they want too, but 
the type conversion code has access to it all the time.
> Foo isn't a stand-in for the real type, it *is* the real type.  Just as
> `int' is the real type, not System.ComponentModel.Int32Converter (the
> actual type that does the string->int conversion).
What about the case where you want an option that accepts standard 
binary abbreviations, e.g. 1K for 1024?  The type of the value is 
clearly an integer, but I need a custom parser to handle the syntax.   
I'd rather not have to wrap the integer in a custom type just to get 
special parsing behavior (e.g. class Int32ThatSupportsBinAbbrevs :-).

That said, if you solve the problem of user thrown exceptions having 
access to the parsing context, then I can just handle this myself in the 
Action code.

-- Jay

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-devel-list/attachments/20080111/5ee77bc8/attachment.html 


More information about the Mono-devel-list mailing list