无为清净楼资源网 Design By www.qnjia.com
通过以下方式之一定义方法,可以将参数发送至 Main 方法。
static int Main(string[] args)
static void Main(string[] args)
【备注】若要在 Windows 窗体应用程序中的 Main 方法中启用命令行参数,必须手动修改 program.cs 中 Main 的签名。 Windows 窗体设计器生成的代码创建没有输入参数的 Main。 也可以使 用 Environment.CommandLine 或 Environment.GetCommandLineArgs 从控制台或 Windows 应用程序中的任何位置访问命令行参数。
Main 方法的参数是表示命令行参数的 String 数组。 一般是通过测试 Length 属性来确定参数是否存在,例如:
if (args.Length == 0) { WriteLine("Hello World."); return 1; }
还可以使用 Convert 类或 Parse 方法将字符串参数转换为数值类型。 例如,下面的语句使用 Parse 方法将 string 转换为 long 数字:
long num = Int64.Parse(args[0]);
也可以使用别名为 Int64 的 C# 类型 long:
long num = long.Parse(args[0]);
还可以使用 Convert 类的方法 ToInt64 完成同样的工作:
long num = Convert.ToInt64(s);
示例
下面的示例演示如何在控制台应用程序中使用命令行参数。 应用程序在运行时采用一个参数,将该参数转换为整数,并计算该数的阶乘。 如果没有提供参数,则应用程序发出一条消息来解释程序的正确用法。
public class Functions { public static long Factorial(int n) { if ((n < 0) || (n > 20)) { return -1; } long tempResult = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } return tempResult; } } class MainClass { static int Main(string[] args) { // Test if input arguments were supplied: if (args.Length == 0) { Console.WriteLine("Please enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } int num; bool test = int.TryParse(args[0], out num); if (test == false) { Console.WriteLine("Please enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } long result = Functions.Factorial(num); if (result == -1) Console.WriteLine("Input must be >= 0 and <= 20."); else Console.WriteLine("The Factorial of {0} is {1}.", num, result); return 0; } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!
无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com
暂无评论...
更新日志
2024年09月27日
2024年09月27日
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】
- 赞多《序章》[FLAC/分轨][129.13MB]
- 群星《完美的她 影视原声带》[320K/MP3][51.98MB]
- 群星《完美的她 影视原声带》[FLAC/分轨][141.05MB]
- 山风点伙.1997-深藏不露【立得】【WAV+CUE】
- 李幸倪.2018-First.Of.All.Live.Concert.3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 李恕权.2003-回·20年全精选2CD【SONY】【WAV+CUE】
- 群星《你就在我身边 电影原声专辑》[320K/MP3][26.68MB]
- 群星《你就在我身边 电影原声专辑》[FLAC/分轨][70.27MB]
- 班得瑞原装进口《20周年精选集》1CD[APE/CUE分轨][303MB]
- 群星.2009-NOON.D.广东.2CD【新世纪】【WAV+CUE】
- 洪卓立.2012-GROWN.UP【英皇娱乐】【WAV+CUE】
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】
- 金佩姗.1997-喜新恋旧【现代派】【WAV+CUE】
- 梁静茹.2007-崇拜【相信音乐】【WAV+CUE】