【问题标题】:Does C# support a variable number of arguments, and how?C# 是否支持可变数量的参数,以及如何支持?
【发布时间】:2012-03-20 15:50:15
【问题描述】:

C# 是否支持可变数量的参数?

如果是,C# 如何支持变量无参数?

有哪些例子?

可变参数有什么用处?

EDIT 1:有什么限制?

编辑 2:问题不是关于可选参数而是可变参数

【问题讨论】:

    标签: c# .net variables arguments params


    【解决方案1】:

    是的。经典的例子是params object[] args:

    //Allows to pass in any number and types of parameters
    public static void Program(params object[] args)
    

    一个典型的用例是在命令行环境中将参数传递给程序,在程序中将它们作为字符串传递。然后程序必须验证并正确分配它们。

    限制:

    • 每个方法只允许使用一个 params 关键字
    • 它必须是最后一个参数。

    编辑:阅读您的编辑后,我做了我的。下面的部分还介绍了实现可变数量参数的方法,但我认为您确实在寻找params 方式。


    也是比较经典的一种,叫做方法重载。你可能已经用过很多次了:

    //both methods have the same name and depending on wether you pass in a parameter
    //or not, the first or the second is used.
    public static void SayHello() {
        Console.WriteLine("Hello");
    }
    public static void SayHello(string message) {
        Console.WriteLine(message);
    }
    

    最后但并非最不重要的一个:可选参数

    //this time we specify a default value for the parameter message
    //you now can call both, the method with parameter and the method without.
    public static void SayHello(string message = "Hello") {
        Console.WriteLine(message);
    }
    

    http://msdn.microsoft.com/en-us/library/dd264739.aspx

    【讨论】:

      【解决方案2】:

      C# 支持使用 params 关键字的可变长度参数数组。

      这是一个例子。

      public static void UseParams(params int[] list)
      {
          for (int i = 0; i < list.Length; i++)
          {
              Console.Write(list[i] + " ");
          }
          Console.WriteLine();
      }
      

      还有更多信息here

      【讨论】:

        【解决方案3】:

        是的,params

        public void SomeMethod(params object[] args)
        

        params 必须是最后一个参数,并且可以是任何类型。不确定它必须是一个数组还是一个 IEnumerable。

        【讨论】:

          【解决方案4】:

          我假设您的意思是variable number of method parameters。如果是这样:

          void DoSomething(params double[] parms)
          

          (或与固定参数混合)

          void DoSomething(string param1, int param2, params double[] otherParams)
          

          限制:

          • 它们都必须是与数组相同的类型(或子类型)
          • 每种方法只能有一个
          • 它们必须在参数列表中排在最后

          目前我能想到的只有这些,虽然可能还有其他人。查看文档以获取更多信息。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-02-29
            • 2013-04-26
            • 2012-01-25
            • 2017-12-21
            • 1970-01-01
            相关资源
            最近更新 更多