How to access command line parameters outside of M

2019-01-25 02:52发布

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?

5条回答
Lonely孤独者°
2楼-- · 2019-01-25 03:19

String[] myStr = Environment.GetCommandLineArgs();

its always good to complete the example.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-25 03:28

Call Environment.GetCommandLineArgs().

查看更多
男人必须洒脱
4楼-- · 2019-01-25 03:34
System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments
查看更多
你好瞎i
5楼-- · 2019-01-25 03:35

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.

查看更多
在下西门庆
6楼-- · 2019-01-25 03:37

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
  }
}
查看更多
登录 后发表回答