Dan*_*son 94
Main方法的参数是一个String数组,表示命令行参数
所以,如果我有一个这样的程序(MyApp.exe):
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}Run Code Online (Sandbox Code Playgroud)
我从命令行开始这样:
MyApp.exe Arg1 Arg2 Arg3Run Code Online (Sandbox Code Playgroud)
Main方法将传递一个包含三个字符串的数组:"Arg1","Arg2","Arg3".
如果需要传递包含空格的参数,请将其用引号括起来.例如:
MyApp.exe "Arg 1" "Arg 2" "Arg 3"Run Code Online (Sandbox Code Playgroud)
当您需要在运行时将信息传递给应用程序时,通常会使用命令行参数.例如,如果您正在编写将文件从一个位置复制到另一个位置的程序,则可能会将这两个位置作为命令行参数传递.例如:
Copy.exe C:\file1.txt C:\file2.txtRun Code Online (Sandbox Code Playgroud)
Dre*_*kes 21
除了其他人的答案之外,您应该注意,如果您的应用程序不使用命令行参数,那么参数在C#中是可选的.
此代码完全有效:
internal static Program
{
private static void Main()
{
// Get on with it, without any arguments...
}
}
Run Code Online (Sandbox Code Playgroud)
除了其他答案。您应该注意到这些参数可以为您提供拖放到.exe文件上的文件路径。即,如果您将任何文件拖放到您的.exe文件上,那么应用程序将被启动,并且arg[0]将包含拖放到其上的文件路径。
static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
Run Code Online (Sandbox Code Playgroud)
this will print the path of the file dropped on the .exe file. e.g
C:\Users\ABCXYZ\source\repos\ConsoleTest\ConsoleTest\bin\Debug\ConsoleTest.pdb
Hence, looping through the args array will give you the path of all the files that were selected and dragged and dropped onto the .exe file of your console app. See:
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
The code sample above will print all the file names that were dragged and dropped onto it, See I am dragging 5 files onto my ConsoleTest.exe app.
And here is the output that I get after that:

| 归档时间: |
|
| 查看次数: |
87536 次 |
| 最近记录: |