c#带参数运行方法 -凯发k8官方网
比如
aa.exe -auto
aa.exe -main
两组后缀,要求分别运行aa的某个线程,比如aa.exe -auto打开from1,aa.exe -main打开from2
由于需要修改program的main方法,需要更加谨慎,因为一个结构清晰的main对于后期维护是一个很好的帮助。以下的代码将解析参数,构造启动窗体,启动窗体三个逻辑分割为三个方法
code
1 static class program
2 {
3 ///
4 /// the main entry point for the application.
5 ///
6 [stathread]
7 static void main(string[] args)
8 {
9
10 application.enablevisualstyles();
11 application.setcompatibletextrenderingdefault(false);
12 //启动有默认启动窗体构造器构造出来的启动窗体
13 application.run(startformcreator(parseargsforformlabel(args)));
14 }
15
16 //从参数中解析启动窗体参数
17 static string parseargsforformlabel(string[] args)
18 {
19 string formlable = string.empty;
20 //如果参数数量大于0则截取第一个参数,否则返回值为string.empty
21 if (args.length > 0)
22 {
23 formlable = args[0];
24 }
25 return formlable;
26 }
27 //根据启动窗体参数构造对应的窗体
28 static form startformcreator(string label)
29 {
30 //如果参数是-auto则构造form1,否则为form2
31 if (label.tolower() == "-auto")
32 {
33 return new form1();
34 }
35 else
36 {
37 return new form2();
38 }
39 }
40 }
aa.exe -auto
aa.exe -main
两组后缀,要求分别运行aa的某个线程,比如aa.exe -auto打开from1,aa.exe -main打开from2
由于需要修改program的main方法,需要更加谨慎,因为一个结构清晰的main对于后期维护是一个很好的帮助。以下的代码将解析参数,构造启动窗体,启动窗体三个逻辑分割为三个方法
code
1 static class program
2 {
3 ///
4 /// the main entry point for the application.
5 ///
6 [stathread]
7 static void main(string[] args)
8 {
9
10 application.enablevisualstyles();
11 application.setcompatibletextrenderingdefault(false);
12 //启动有默认启动窗体构造器构造出来的启动窗体
13 application.run(startformcreator(parseargsforformlabel(args)));
14 }
15
16 //从参数中解析启动窗体参数
17 static string parseargsforformlabel(string[] args)
18 {
19 string formlable = string.empty;
20 //如果参数数量大于0则截取第一个参数,否则返回值为string.empty
21 if (args.length > 0)
22 {
23 formlable = args[0];
24 }
25 return formlable;
26 }
27 //根据启动窗体参数构造对应的窗体
28 static form startformcreator(string label)
29 {
30 //如果参数是-auto则构造form1,否则为form2
31 if (label.tolower() == "-auto")
32 {
33 return new form1();
34 }
35 else
36 {
37 return new form2();
38 }
39 }
40 }
总结
- 上一篇:
- 下一篇: