C#中的params参数(参数数组):
1、params参数是数组。调用方式可以数组方式,也可以单个元素方式。
static void test(String name,params int[] scores)
{
StringBuilder sb = new StringBuilder();
foreach(int i in scores)
{
sb.AppendFormat("{0}-",i);
}
Console.WriteLine("{0}你好,你的Scores is {1}",name,sb);
}
test("刘德华",new int[]{1,2,3});//以数组方式调用
test("周星驰",80,90,100,98);//单个元素方式调用
test("梁朝伟");//无参数方式调用
2、params参数必须是最后一个参数。
3、params参数不能是ref或out参数。
4、params参数不是方法重载的签名特性。
5、当调用方法而没有传递params参数时,编译器实际传递一个空数组(长度为0的数组)。
{
分析:当以单个元素传递params参数时,实际编译器自动生成一个数组:该数组长度等于这些参数元素个数,元素就是这些单个参数。然后吧该数组传递到方法中。
例如:test("刘德华",10,5);系统实际执行如下操作:
int[] temp = new int[2]; temp[0] = 10; temp[1] = 5 ; test("刘德华",temp).
}
扩展方法:
//扩展方法
/*
* 1、扩展方法必须放在静态类中。
* 2、扩展方法必须是静态的。(静态类中不能存在实例成员)
* 3、要扩展的类型必须是第一个参数,且以this为前缀(扩展类实例),后面可以有普通参数
* 4、使用扩展方法时,必须把扩展方法所在的静态类加入使用的命名空间
* 5、扩展类型的子类也自动具有同样的扩展方法(继承)
*/
static class Util
{
public static int GetPhqInt(this Animal animal)
{
return animal.GetHashCode() + 10000000;
}
internal static void PrintClassName(this Animal animal)
{
Console.WriteLine(animal.getClassName());
}
internal static void Add100(this int num)
{
Console.WriteLine("{{加100之后的数据:{0}}}",num+100);
}
}
调用:
animal.PrintClassName();
pig.PrintClassName();
Console.WriteLine(dog.GetPhqInt());
int a = 8;
a.Add100();