C#_parameter array

Sometimes we want the number of parameters to be variable.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string fullName;

            fullName = Combine(Directory.GetCurrentDirectory(), "bin", "config", "index.html");

            Console.WriteLine(fullName);

            fullName = Combine(Environment.SystemDirectory, "Temp", "index.html");

            Console.WriteLine(fullName);

            fullName = Combine(new string[] { "C:\\", "Data", "HomeDir", "index.html" });

            Console.WriteLine(fullName);

            Console.ReadKey();
        }

        static string Combine(params string[] paths)
        {
            string result = string.Empty;
            foreach (string path in paths)
            {
                result = Path.Combine(result, path);
            }
            return result;
        }
    }
}

//D:\C#\ConsoleApp1\ConsoleApp1\bin\Debug\bin\config\index.html
//C:\WINDOWS\system32\Temp\index.html
//C:\Data\HomeDir\index.html

*PathEx.Combine() is exactly equivalent to Path.Combine(), except that it can handle a variable number of parameters instead of only two.

The Combine method accepts a variable number of arguments, either comma-separated string arguments, or a single array of strings, the former being called the expanded form of the method call , and the latter being the normal form.

To achieve this effect, the Combine method needs to:

  1. Add the params keyword before the last parameter of the method declaration
  2. Declare the last parameter as an array

The parameter array should pay attention to the following points:

  • The parameter array does not have to be the only parameter of the method , but must be the last. Since it can only be placed at the end, there can only be at most one parameter array.
  • The caller may specify zero actual parameters corresponding to the parameter array , which causes the passed parameter array to contain zero data items.
  • Parameter arrays are type-safe - the type of the actual parameter must be compatible with the type of the parameter array.
  • Instead of passing a comma-separated list of parameters, the caller can pass an actual array. The final generated CIL code is the same.
  • If the implementation of the target method requires a minimum number of parameters, please explicitly specify the parameters that must be provided in the method declaration. This way, omission of a required parameter results in an error from the compiler, without having to rely on runtime error handling. For example, using  int Max(int ​​first,params int[] operands) instead of int Max(params int[] operands) ensures that at least one integer argument is passed to Max.

Guess you like

Origin blog.csdn.net/ashmoc/article/details/122246616