当前位置: 移动技术网 > IT编程>开发语言>.net > 浅谈Main方法的参数

浅谈Main方法的参数

2017年12月12日  | 移动技术网IT编程  | 我要评论
通过以下方式之一定义方法,可以将参数发送至 main 方法。 static int main(string[] args) static void main(strin

通过以下方式之一定义方法,可以将参数发送至 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;
 }
 }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

相关文章:

验证码:
移动技术网