温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何将参数上传到Main方法

发布时间:2021-09-16 11:09:50 来源:亿速云 阅读:136 作者:柒染 栏目:开发技术

如何将参数上传到Main方法,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

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

看完上述内容,你们掌握如何将参数上传到Main方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI