NDesk.Options
尽管您必须自己编写一些验证代码,但您可以使用 来模拟这一点。
您可以为NDesk.Options
默认选项(“<>”)注册一个处理程序。该处理程序将为您示例中的每个连接运行。每次遇到默认选项的值时,您都可以创建一个连接设置对象,并在提供正常选项时填写最新的。
public class ConnectionListParser : OptionSet
{
public class ConnectionSettings
{
public string Name { get; set; }
public string Servername { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
public List<ConnectionSettings> Connections {get;} = new List<ConnectionSettings>();
public ConnectionListParser() {
Add("<>", x => {
Connections.Add(new ConnectionSettings() {
Name = x
});
});
Add("s:", x => Connections.Last().Servername = x);
Add("u:", x => Connections.Last().Username = x);
Add("p:", x => Connections.Last().Password = x);
}
}
用法:
var opts = new ConnectionListParser();
var remain = opts.Parse("conn1 -sservername1 -uusername1 -ppassword1 conn2 -sservername2 -uusername2 -ppassword2".Split(' '));
// or opts.Parse(args) when you have actual command line arguments to parse
foreach(var c in opts.Connections) {
Console.WriteLine($"Connection '{c.Name}': Username={c.Username};Password={c.Password};Servername={c.Servername}");
}