[英]c# Command Line arguments
我试图让我的程序从命令行参数运行,所以我的代码中有 3 个选项供您选择运行。
问题是我想解析端口和参数,我该怎么做?
每个选项都有不同的程序配置。 我的尝试如下所示; 所以在程序内部,我还想将端口作为参数传递,所以当我在控制台中编写“程序 1 5656”时。 应用程序看到它运行的第一个选项 1,然后将 5656 解析为端口变量。
我在下面尝试过,但是当我输入命令时,它给了我错误的选项,因为它开始选项 2 而不是 1。
class MainClass
{
static void Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 1)
{
int port = int.Parse(args[1]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
if (args.Length == 2)
{
int port = int.Parse(args[2]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
if (args.Length == 3)
{
int port = int.Parse(args[3]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
}
}
看来,您希望port
是最后一个参数:
static void Main(string[] args) {
// if we have parameters...
if (args.Length > 0) {
//TODO: int.TryParse is a better choice
int port = int.Parse(args[args.Length - 1]); // ... port is the last one
server = new TcpListener(IPAddress.Any, port);
// Rest of the program
}
}
编辑 :如果您只想传递两个参数 ( option
和port
)
static void Main(string[] args) {
if (args.Length == 2) {
//TODO: int.TryParse is a better choice
int option = int.Parse(args[0]);
int port = int.Parse(args[1]);
// Rest of the program, e.g.
if (option == 1) {
...
}
else if (option == 2) {
...
}
else if (option == 3) {
...
}
}
}
这是你想要的吗?
class MainClass
{
static void Main(string[] args)
{
// Test if input arguments were supplied:
var switchvalue = int.Parse(args[0]);
if (switchvalue == 1)
{
int port = int.Parse(args[1]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
if (switchvalue == 2)
{
int port = int.Parse(args[1]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
if (switchvalue == 3)
{
int port = int.Parse(args[1]);
server = new TcpListener(IPAddress.Any, port);
//Rest of the program
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.