public class CmdParser { private DictionarykeyValuePairs = new Dictionary (); static public CmdParser Parse(string[] args) { return new CmdParser(args.ToList()); } static public CmdParser Parse(List args) { return new CmdParser(args); } private CmdParser(List args) { if (args.Count <= 0) return; for(int keyIndex = 0; keyIndex < args.Count; keyIndex++) { var key = args[keyIndex]; if (!key.StartsWith("-")) continue; List values = new List (); for (int valueIndex = keyIndex + 1; valueIndex < args.Count; valueIndex++) { if (args[valueIndex].StartsWith("-")) break; values.Add(args[valueIndex]); } Command cmd = new Command(values); keyValuePairs.Add(key, cmd); } } public bool Has(string key) { return keyValuePairs.ContainsKey(key); } public Command this[string key] { get { return keyValuePairs[key]; } } }
public class Command { private ListmCmds; private int mIndex = 0; public Command(List cmds) { this.mCmds = cmds; } public string First { get { mIndex = 0; return mCmds[mIndex]; } } public string Last { get { mIndex = mCmds.Count - 1; return mCmds[mIndex]; } } public string Get(int index) { if (index < mCmds.Count) { mIndex = index; return mCmds[mIndex]; } return null; } public bool HasNext { get { return mIndex < mCmds.Count - 1; } } public string Next { get { if (HasNext) return mCmds[mIndex++]; return null; } } public List All { get { return mCmds; } } }
用法:
string cmd = "-hello,world,!,-Hi,man";string[] args = cmd.Split(",");var parser = CmdParser.Parse(args);//获取单个if (parser.Has("-Hello")){ parser["-Hello"].First;}//获取多个if (parser.Has("-Hello")){ parser["-Hello"].All;}//其它用法看代码,但基本没什么意义,预留而已.....