版权声明:转载请注明出处 https://blog.csdn.net/le_17_4_6/article/details/86607588
方法的参数、参数数组params的使用、
-
值参数(即形参)
编译器为值参数分配存储空间,然后将对应的实参的值拷贝到形参中
对形参的改变不会影响到实参 -
引用参数
- 引用参数与实参变量共用一个存储单元
- ref仅对其后的参数有效,不能应用于整个参数表
- 调用方法时,也用ref修饰实参变量
- 实参的类型与形参类型必须完全匹配
- 实参必须是变量,不能是常量或表达式
- ref参数在调用前必须明确赋值
-
输出参数
- 只能从方法中传出值,不能从方法调用处接收实参数据
- 调用方法时,用out修饰实参变量
-
参数数组 params
- 使用params关键字指定一个参数可变长的参数表
- 一个方法中只能声明一个params参数,如果还有其他常规参数,则params参数应放在参数表的最后
- 用params修饰符声明的参数是一个一维数组类型,例如,可以是int[]、string[]、double[]、但不能是int[ , ]、string[ , ]等
- 当调用具有params参数的方法时,可以作为一个元素列表或作为一个数组传递给params参数
- params参数在内部会进行数据的复制,不能将params参数与ref和out修饰符组合起来使用
使用ref引用参数来进行变量值的交换:
using System;
namespace ParamExp2
{
public class A
{
public void swap1(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
public void swap2(ref int x, ref int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
int xx = 60, yy = 70;
a.swap1(xx, yy);
Console.WriteLine("{0},{1}", xx, yy);
a.swap2(ref xx, ref yy);
Console.WriteLine("{0},{1}", xx, yy);
Console.ReadLine();
}
}
}
从一个不定长参数数组中获得最大值和最小值:
using System;
namespace ParamExp3
{
public class A
{
public void MaxMin(out int max, out int min, params int[] a)
{
if (a.Length == 0)
{
max = min = -1;
return;
}
max = min = a[0];
for (int i = 1; i < a.Length; i++)
{
if (a[i] > max) max = a[i];
if (a[i] < min) min = a[i];
a[i]++;
}
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
int maxNumber, minNumber;
int[] nums ={ 78, 32, 95, 73, 43 };
a.MaxMin(out maxNumber, out minNumber, 48, 92, 62, 52, 78);
Console.WriteLine("Max={0},Min={1}", maxNumber, minNumber);
int[] bb ={ 67, 83, 24, 45, 56 };
a.MaxMin(out maxNumber, out minNumber, bb);
Console.WriteLine("Max={0},Min={1}", maxNumber, minNumber);
Console.ReadLine();
}
}
}