I am writing a .NET class that needs to parse the command line of the process. I don't want to have a dependency between the Main() method and that class. How can the class access the command line?
问题:
回答1:
Call Environment.GetCommandLineArgs()
.
回答2:
If you use .NET Compact Framework, Environment.GetCommandLineArgs() method isn't implemented and System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments returns always empty string, so you must use main function and pass arguments to your others classes.
An example :
[MTAThread]
static void Main(String[] commandLineArguments)
{
CommandLineHelper.parse(commandLineArguments);
}
public static class CommandLineHelper
{
public static void parse(String[] commandLineArguments) {
// add your code here
}
}
回答3:
Create a class that holds your application's options. In the main method create an instance of that class, initialise it with the command line arguments, and pass it in to the classes that need it.
Alternatively, you could have the class initialised at any time thereafter by having it created via a CustomConfigClass.Create()
method that uses Environment.GetCommandLineArgs()
.
The first option would be my recommendation, because it makes the class easier to prepare for unit testing and switching to an alternative method of configuration at a later date without breaking the application due to a dependency on the command line.
回答4:
System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments
回答5:
String[] myStr = Environment.GetCommandLineArgs();
its always good to complete the example.