参量参数:(params 关键字)
多个变量可以由一个参量参数来代表
代码:
public class MyClass
{
public static void UseParams(params int[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
Console.WriteLine();
}
public static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}输出
1
2
3
1
a
test
10
11
12
输出参数、引用参数:(out、ref关键字)
out调用者必须在调用方法之后初始化参数的值
ref调用者必须在调用方法之前首先初始化参数的值
代码:
class Program
{
static void Main(string[] args)
{
//输出参数
Point p = new Point(10, 12);
int x, y;//输出参数不需要赋初值
p.GetPoint(out x, out y);
Console.WriteLine("p({0},{1})", x, y);
//引用参数
Point2 p1 = new Point2(12, 23);
int x1 = 0, y1 = 0;//引用参数一定要赋初值
p1.GetPoint(ref x1, ref y1);
Console.WriteLine("p1({0},{1})", x1, y1);
// 参数数组
int[] a = { 1, 2, 3, 4, 5 };
Array.F(a);
Array.F(10, 20, 30, 60, 50);//F(new int[] {10, 20, 30, 60, 50})
Array.F();
Console.ReadLine();
}
}
/// <summary>
/// 输出参数可返回多个值
/// </summary>
class Point
{
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(out int x, out int y)
{
y = this.Y;
x = this.X;
}
private int X, Y;
}
/// <summary>
/// 引用参数
/// </summary>
class Point2
{
int X, Y;
public Point2(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(ref int x, ref int y)
{
y = this.Y;
x = this.X;
}
}
/// <summary>
/// 参数数组
/// </summary>
class Array
{
public static void F(params int[] args)
{
Console.WriteLine("数组长度为:{0}", args.Length);
foreach (int i in args)
{
Console.WriteLine("{0}", i);
}
Console.WriteLine();
}
}