【发布时间】:2019-11-13 21:45:35
【问题描述】:
我想以这种特定格式将参数传递给 c# 控制台应用程序。 假设我的应用程序的 exe 名称是 SmsSender, 我想在我的 cmd 中使用这种格式: SMSSender -m 消息 -p 电话号码
我该怎么做?
【问题讨论】:
-
请向我们展示您目前的尝试。
我想以这种特定格式将参数传递给 c# 控制台应用程序。 假设我的应用程序的 exe 名称是 SmsSender, 我想在我的 cmd 中使用这种格式: SMSSender -m 消息 -p 电话号码
我该怎么做?
【问题讨论】:
请参阅此 Microsoft Docs How to Display arguments
因此,在您的 Main 方法中的控制台应用程序中,您将拥有如下内容:
class CommandLine
{
static void Main(string[] args)
{
// The Length property provides the number of array elements.
Console.WriteLine($"parameter count = {args.Length}");
// Get values using the `args` array in your case you will have:
// args[0] = "-m";
// args[1] = "message";
// args[2] = "-p";
// args[3] = "phonenumber";
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"Arg[{i}] = [{args[i]}]");
}
}
}
【讨论】:
您只需将该命令写入命令提示符窗口,就像您在其中编写的那样
在您的 c# 应用程序中,您有一个 static void Main(string[] args),而 args 数组将有 4 个元素:
args[0] = "-m";
args[1] = "message";
args[2] = "-p";
args[3] = "phonenumber";
但请注意,如果您不将消息包含在“引号”中(在命令提示符中),那么消息中的每个单词都将是 args 中的不同条目
【讨论】: