现在的位置: 首页 > 综合 > 正文

命令行参数

2013年09月05日 ⁄ 综合 ⁄ 共 1453字 ⁄ 字号 评论关闭
C# 程序员参考  

命令行参数

Main 方法可以使用参数,在这种情况下它采用下列形式之一:

static int Main(string[] args)
static void Main(string[] args)

Main 方法的参数是表示命令行参数的 string 数组。通常通过测试 Length 属性来检查参数是否存在,例如:

if (args.Length == 0) 
{
   Console.WriteLine("Please enter a numeric argument."); 
   return 1; 
}

还可以使用 Convert 类或 Parse 方法将字符串参数转换为数值类型。例如,下面的语句使用 Int64 类上的 Parse 方法将字符串转换为 long 型数字:

long num = Int64.Parse(args[0]);

也可以使用别名为 Int64 的 C# 类型 long

long num = long.Parse(args[0]);

还可以使用 Convert 类的方法 ToInt64 完成同样的工作:

long num = Convert.ToInt64(s);

有关更多信息,请参见 parse 方法Convert 类

示例

在此示例中,程序在运行时采用一个参数,将该参数转换为一个长数字,并计算该数字的阶乘。如果没有提供参数,则程序发出一条消息来解释程序的正确用法。

// Factorial_main.cs
// arguments: 3
using System; 
public class Factorial 
{
   public static long Fac(long i)
   {
      return ((i <= 1) ? 1 : (i * Fac(i-1)));
   }
}

class MainClass 
{
   public 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; 
      }

      // Convert the input arguments to numbers:
      try 
      {
           long num = long.Parse(args[0]); 
           Console.WriteLine("The Factorial of {0} is {1}.", 
                        num, Factorial.Fac(num)); 
           return 0;
      }
      catch (System.FormatException)
      {
         Console.WriteLine("Please enter a numeric argument."); 
         Console.WriteLine("Usage: Factorial <num>"); 
         return 1; 
      }
   }
}

输出

The Factorial of 3 is 6.

以下是该程序的两个运行示例(假定程序名为 Factorial.exe)。

运行示例 #1:

Enter the following command line:
Factorial 10
You get the following result:
The Factorial of 10 is 3628800.

运行示例 #2:

Enter the following command line:
Factorial
You get the following result:
Please enter a numeric argument.
Usage: Factorial <num>

有关使用命令行参数的更多示例,请参见创建和使用 C# DLL 中的示例。

抱歉!评论已关闭.