参数数组一些值得注意的特征(params)

参数数组的应用场景:它允许我们在调用一个方法时提供数量可变的参数,而不是由方法事先固定好的数量

一个例子:有时候路径中的文件夹数量是大于一的,调用者希望将额外的文件夹关联起来,以构成一个完整的路径,那么如何编码呢?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 学习
{
    class 参数数组
    {
        public static void MyParams(params string[] paths)
        {
            string resuit = string.Empty;//表示空字符串
            foreach (string path in paths)
            {
                resuit = System.IO.Path.Combine(resuit, path);//合并两个字符串路径

            }
            Console.WriteLine(resuit);//在屏幕上打印出来
        }
    }
}


主函数中调用时

          //有四个参数,Directiony.GetcurrentDirectiony()表示获取应用程序当前的目录
           参数数组.MyParams(Directory.GetCurrentDirectory(),"bin","config","index.html");
            //三个参数,Environment.SystemDirectiony表示获取系统目录的完全限定目录
           参数数组.MyParams(Environment.SystemDirectory,"Temp","index.html");
            //参数用一个数组来传递
           参数数组.MyParams(new string[]{@"C:\","Temp","index.html"});

咱们看看结果:

参数数组有以下一些值得注意的特征

  • 参数数组不一定是方法声明中的唯一参数,但是,参数数组必须是方法声明中的最后一个参数。
  • 调用者可以为参数数组指定0个参数,这会造成包含0个数据项的一个数组
  • 调用者可以显示的提供一个数组,而不是以逗号分割参数列表,最终生成的CIL代码是一样的
  • 使用参数数组我们可以讲类型相同,数量可变得参数传递给一个方法
posted @ 2012-04-12 09:25  xinyebs  阅读(312)  评论(0编辑  收藏  举报