I thought of several more advanced versions. There was one that searches for more attributes that specify parameters keys and the code that handles them. There was also one that uses the stored entries and adds them to the background task. In both cases, any validation and further code for each parameter exists outside the class below in other modules.
After this point, you can see we simplified C++'s singleton paradigm with C#'s "sealed" keyword and the Program.Singleton attribute for private instantion.
Note the regular-expression matches “--key=value” and “--option” style parameters, and it accepts “/” instead of “--” for POSIX and DOS style parameters.
Related Posts: Part 1 2 3 4
using System.Collections.Specialized ;
using System.Text.RegularExpressions ;
using System.Diagnostics ;
using System.Collections ;
using System;
namespace Application
{
[Program.Singleton]
public sealed class Parameter
{
static StringDictionary parameter = new StringDictionary() ;
private Parameter()
{
Program.Parse += Parse ;
}
~Parameter()
{
Program.Parse -= Parse ;
}
static Parameter()
{
#if DEBUG
parameter.Add( "debug", "true" ) ;
#endif
}
static public void Parse( string[] args )
{
foreach( string s in args )
{
Match m = Regex.Match( s, @"^(-{1,2}|/)((?
if( ! m.Success )
{
Debug.WriteLine( "Invalid Parameter: {0}", s ) ;
continue ;
}
Group o = m.Groups[ "option" ] ;
Group k = m.Groups[ "key" ] ;
Group v = m.Groups[ "value" ] ;
if( ! String.IsNullOrEmpty( o.Value ) )
parameter[ o.Value ] = "true" ;
else
{
parameter[ k.Value ] = v.Value ;
}
}
}
static public string Value( string key )
{
return parameter[ key ] ;
}
}
}