C# params参数的应用

为了将方法声明为能够接受可变数量参数的方法,咱们能够使用params关键字来声明数组,以下所示:数组

public static Int32Add(params Int32[] values)dom

{性能

     Int32 sum = 0;内存

     for (Int32 x = 0; x < values.Length; x++)string

     {it

     sum += values[x];编译

     }class

     return sum;object

}foreach

     只有方法的最后一个参数才能够标记params,该参数必须标识一个一维数组,但类型不限。对方法的最后一个参数传递null或者0个数目的数组的引用都是合法的,以下面代码调用上面Add方法,编译正常,运行正常,和指望同样结果为0:

public static void Main()

{

     Console.WriteLine(Add());

}

     下面看一下如何编写一个能够接受任意数量、任意类型的参数的方法,也就是把上面方法的Int32改为Object[]就能够了:

public static void Main()

{

     DisplayTypes(new Object(), new Random(), "string", 10);

}

public static void DisplayTypes(params Object[] objects)

{

     foreach(Object o in objects)

     {

          Console.WriteLine(o.GetType());   

     }

}

输出:

System.Object

System.Random

System.String

System.Int32

 

注意,对于可接受可变数量参数的方法的调用会对性能形成必定的损失,由于数组是在堆上分配的,数组的元素还得初始化,数组的内存还得被垃圾回收器回收,为了减小这种不必的性能损失,咱们但愿定义几个没有params关键字的重载方法,如System.String类的Concat方法,以下:

public static string Concat(object arg0);

public static string Concat(params object[] args);

public static string Concat(params string[] values);

public static string Concat(object arg0, object arg1);

public static string Concat(string str0, string str1);

public static string Concat(object arg0, object arg1, object arg2);

public static string Concat(string str0, string str1, string str2);

public static string Concat(object arg0, object arg1, object arg2, object arg3);

public static string Concat(string str0, string str1, string str2, string str3);

相关文章
相关标签/搜索