Best way to read commandline parameters in console

2019-02-11 17:10发布

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.

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.

4条回答
等我变得足够好
2楼-- · 2019-02-11 17:31

The first way is better because it's simpler.

查看更多
The star\"
3楼-- · 2019-02-11 17:37

Do you know getopt? There is a port for C# on codeplex: http://www.codeplex.com/getopt

查看更多
【Aperson】
4楼-- · 2019-02-11 17:38

Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think about.

Also I don't like the "magic" that puts the args in the method parameter for the first way.

查看更多
forever°为你锁心
5楼-- · 2019-02-11 17:45

To me the first way seems more intuitive because that is how I have been doing it since my C/C++ days.

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.

Regards,

kgr

查看更多
登录 后发表回答