.net 在控制台应用程序中读取命令行参数的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/82838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to read commandline parameters in console application
提问by osp70
Below are two ways of reading in the commandline parameters. The first is the way that I'm accustom to seeing using the parameter in the main. The second I stumbled on when reviewing code. I noticed that the second assigns the first item in the array to the path and application but the first skips this.
下面是两种读取命令行参数的方法。第一个是我习惯看到在 main.js 中使用参数的方式。我在代码时偶然发现的第二个。我注意到第二个将数组中的第一项分配给路径和应用程序,但第一个跳过了这个。
Is it just preference or is the second way the better way now?
这只是偏好还是第二种方式现在更好?
Sub Main(ByVal args() As String)
For i As Integer = 0 To args.Length - 1
Console.WriteLine("Arg: " & i & " is " & args(i))
Next
Console.ReadKey()
End Sub
Sub Main()
Dim args() As String = System.Environment.GetCommandLineArgs()
For i As Integer = 0 To args.Length - 1
Console.WriteLine("Arg: " & i & " is " & args(i))
Next
Console.ReadKey()
End Sub
I think the same can be done in C#, so it's not necessarily a vb.net question.
我认为在 C# 中也可以这样做,所以它不一定是 vb.net 的问题。
回答by David Thibault
Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think about.
第二种方法更好,因为它可以在 main() 之外使用,所以当你重构时,它不需要考虑一件事。
Also I don't like the "magic" that puts the args in the method parameter for the first way.
此外,我不喜欢将 args 放在第一种方法的方法参数中的“魔法”。
回答by Thomas
Do you know getopt? There is a port for C# on codeplex: http://www.codeplex.com/getopt
你知道getopt吗?Codeplex 上有一个 C# 端口:http: //www.codeplex.com/getopt
回答by user12861
The first way is better because it's simpler.
第一种方法更好,因为它更简单。
回答by user12861
To me the first way seems more intuitive because that is how I have been doing it since my C/C++ days.
对我来说,第一种方式似乎更直观,因为这就是我从 C/C++ 时代起就一直在做的方式。
If your commandline has one too many switches please do take a look at getopt that Thomas recommends. It's quite useful. I haven't had a look at C# port of the same though.
如果您的命令行有太多开关,请查看 Thomas 推荐的 getopt。它非常有用。我还没有看过相同的 C# 端口。
Regards,
问候,
kgr
公斤

