浅谈Main方法的参数

所属分类: 网络编程 / ASP.NET 阅读数: 2090
收藏 0 赞 0 分享

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

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

更多精彩内容其他人还在看

ASP.NET 水晶报表打印功能实现代码

ASP.NET下的水晶报表打印,据我所知有以下几种办法可以打印
收藏 0 赞 0 分享

ASP.Net 图片存入数据库的实现代码

在很多时候,我们有这样的需求:把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。
收藏 0 赞 0 分享

让Silverlight 2.0动画动起来Making Silverlight 2.0 animation Start(不能运动原因)

Microsoft Expression Blend 2 制作动画个人感觉倒像3DMAX 可以自动捕捉关键帧
收藏 0 赞 0 分享

asp.net Reporting Service在Web Application中的应用

由于我们这个项目中使用微软的报表服务(Reporting Services)作为报表输出工具,本人也对它进行一点点研究,虽没有入木三分,但这点知识至少可以在大部分Reporting Service的场景中应用。
收藏 0 赞 0 分享

C# 文件上传 默认最大为4M的解决方法

.net中默只能上传小于4m的文件,大于4M将无法显示页面.那么如何设置来使imputfile能上传更大的文件呢
收藏 0 赞 0 分享

asp.net 购物车实现详细代码

asp.net 购物车实现详细代码
收藏 0 赞 0 分享

asp.net repeater实现批量删除时注册多选框id到客户端

repeater批量删除时注册多选框id到客户端的实现代码
收藏 0 赞 0 分享

asp.net aspnetpager分页统计时与实际不符的解决办法

最近分页方面根据实际需要修改了一些函数
收藏 0 赞 0 分享

iis 服务器应用程序不可用的解决方法

访问页面时提示 服务器应用程序不可用,大家可以按照下面的方法重新注册下,应该能好点
收藏 0 赞 0 分享

asp.net button 绑定多个参数

asp.net button 绑定多个参数的代码
收藏 0 赞 0 分享
查看更多