out
当一个函数(方法)有不同类型的返回值时,可以使用out参数。
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int max = 0, min = 0, sum = 0, avg = 0;
string a;
bool b;
double c;
Test(nums, out max, out min, out sum, out avg, out a, out b, out c);
Console.WriteLine(max);
Console.WriteLine(min);
Console.WriteLine(sum);
Console.WriteLine(avg);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
public static void Test(int[] nums, out int max, out int min, out int sum, out int avg, out string a, out bool b, out double c)
{
max = nums[0];
min = nums[1];
sum = nums[2];
avg = nums[3];
a = "hello world";
b = true;
c = 1.23123;
}
}
Ref
使用ref后可以将变量带入方法改变,并带出。
使用ref的参数外必须赋值,而在方法内可以不赋值。
static void Main()
{
int a = 5000;
Test(ref a);
Console.WriteLine(a);
}
public static void Test(ref int a)
{
a += 500;
}
Params
当不想定义变量传参数到函数中时, 可以使用params 关键字
Params 关键字必须是形参最后一个元素, 且一个函数只能有一个params。
static void Main()
{
Test("Hello",17,13,14);
}
public static void Test(string name, params int[] nums)
{
int size = nums.Length;
Console.WriteLine(size);
}