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?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
String[] myStr = Environment.GetCommandLineArgs();
its always good to complete the example.
Call
Environment.GetCommandLineArgs()
.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 usesEnvironment.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.
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 :