导航

04-004 Configuration 之 CommandLineConfigurationSource

Posted on 2015-03-16 17:58  DotNet1010  阅读(214)  评论(0)    收藏  举报

CommandLine 的例子: 前面的符号可以是 短横,两个短横“--” 或者 反斜杠”/"

 args = new string[]
                {
                    "Key1=Value1",
                    "--Key2=Value2",
                    "/Key3=Value3",
                    "--Key4", "Value4",
                    "/Key5", "Value5"
                };
args = new string[]
                {
                    "-K1=Value1",
                    "--Key2=Value2",
                    "/Key3=Value3",
                    "--Key4", "Value4",
                    "/Key5", "Value5",
                    "/Key6=Value6"
                };

 下面是Load方法的代码:

 public override void Load()
        {
            var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            string key, value;
            var argIndex = 0;

            while (argIndex < Args.Length)
            {
                var currentArg = Args[argIndex];
                var keyStartIndex = 0;

                if (currentArg.StartsWith("--"))
                {
                    keyStartIndex = 2;
                }
                else if (currentArg.StartsWith("-"))
                {
                    keyStartIndex = 1;
                }
                else if (currentArg.StartsWith("/"))
                {
                    // "/SomeSwitch" is equivalent to "--SomeSwitch" when interpreting switch mappings
                    // So we do a conversion to simplify later processing
                    currentArg = string.Format("--{0}", currentArg.Substring(1));
                    keyStartIndex = 2;
                }

                var separator = currentArg.IndexOf('=');

                if (separator < 0)
                {
                    // If there is neither equal sign nor prefix in current arugment, it is an invalid format
                    if (keyStartIndex == 0)
                    {
                        throw new FormatException(Resources.FormatError_UnrecognizedArgumentFormat(currentArg));
                    }

                    // If the switch is a key in given switch mappings, interpret it
                    if (_switchMappings != null && _switchMappings.ContainsKey(currentArg))
                    {
                        key = _switchMappings[currentArg];
                    }
                    // If the switch starts with a single "-" and it isn't in given mappings , it is an invalid usage
                    else if (keyStartIndex == 1)
                    {
                        throw new FormatException(Resources.FormatError_ShortSwitchNotDefined(currentArg));
                    }
                    // Otherwise, use the switch name directly as a key
                    else
                    {
                        key = currentArg.Substring(keyStartIndex);
                    }

                    argIndex++;

                    if (argIndex == Args.Length)
                    {
                        throw new FormatException(Resources.FormatError_ValueIsMissing(Args[argIndex - 1]));
                    }

                    value = Args[argIndex];
                }
                else
                {
                    var keySegment = currentArg.Substring(0, separator);

                    // If the switch is a key in given switch mappings, interpret it
                    if (_switchMappings != null && _switchMappings.ContainsKey(keySegment))
                    {
                        key = _switchMappings[keySegment];
                    }
                    // If the switch starts with a single "-" and it isn't in given mappings , it is an invalid usage
                    else if (keyStartIndex == 1)
                    {
                        throw new FormatException(Resources.FormatError_ShortSwitchNotDefined(currentArg));
                    }
                    // Otherwise, use the switch name directly as a key
                    else
                    {
                        key = currentArg.Substring(keyStartIndex, separator - keyStartIndex);
                    }

                    value = currentArg.Substring(separator + 1);
                }

                // Override value when key is duplicated. So we always have the last argument win.
                data[key] = value;
                argIndex++;
            }

            ReplaceData(data);
        }

 上述代码有个 switchMappings 这个可以实现Key的替换 (这是为了简化参数 比如 Key 变成  K ) 见下面的代码:

   var args = new string[]
                {
                    "-K1=Value1",
                    "--Key2=Value2",
                    "/Key3=Value3",
                    "--Key4", "Value4",
                    "/Key5", "Value5",
                    "/Key6=Value6"
                };
            var switchMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
                {
                    { "-K1", "LongKey1" },                 //K 替换为 LongKey1
                    { "--Key2", "SuperLongKey2" },         //Key2 替换为 SuperLongKeys
                    { "--Key6", "SuchALongKey6"}
                };
            var cmdLineConfig = new CommandLineConfigurationSource(args, switchMappings);

            cmdLineConfig.Load();

            Assert.Equal(6, cmdLineConfig.Data.Count);
            Assert.Equal("Value1", cmdLineConfig.Data["LongKey1"]);
            Assert.Equal("Value2", cmdLineConfig.Data["SuperLongKey2"]);
            Assert.Equal("Value3", cmdLineConfig.Data["Key3"]);
            Assert.Equal("Value4", cmdLineConfig.Data["Key4"]);
            Assert.Equal("Value5", cmdLineConfig.Data["Key5"]);
            Assert.Equal("Value6", cmdLineConfig.Data["SuchALongKey6"]);