ref
ref可以将值类型的参数转换成引用类型的参数进行传递
引用类型在进行交换的时候不需要加ref
在明确要改变值的类型的时候确定需要引用类型进行传递可以使用ref
比如说,当我们需要用方法交换数值的时候,直接交换只是开辟了一块新的空间进行存储交换,并没有进行实质的交换。
例`namespace ConsoleApp1
{
public class MyClass
{
//数值是值类型进行交换时转换成引用类型
public void sum(ref int a, ref int b)
{
//如果不加ref 只是在内存中重新开辟一片空间进行存储
int temp = a;
a = b;
b = temp;
}
}
class Program
{
static void Main(string[] args)
{
MyClass my = new MyClass ( );
int i = 5;
int j = 7;
my.sum (ref i, ref j);
Console.WriteLine (i.ToString());
Console.WriteLine (j.ToString ( ));
Console.ReadKey ( );
}
}
}`
out
当一个方法需要多个返回值的时候可以使用out 关键字进行传递
使用out关键字可以将参数作为返回值使用
例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
//当一个方法需要多个返回值的时候用out关键字
//例如 :比较大小,需要传出最大值和最小值的时候
public class Math
{
//要想将参数作为返回值使用,需要怎加一个参数,并用out 修饰
public int Maxmin(int a,int b, int c,out int min)
{
//参数初始化
min = 0;
int m = a;
if (m>b)
{
m = b;
}
if (m>c)
{
m = c;
}
//把m这个最小值付给 min参数
min = m;
int max = a;
if (max<b)
{
max = b;
}
if (max<c)
{
max = c;
}
return max;
}
}
class Program
{
static void Main(string[] args)
{
Math m = new Math ( );
int j = 15;
int k = 45;
int l = 4;
//定义变量接受参数值
int min = 0;
//通过out将min传回
int max= m.Maxmin (j, k, l,out min);
Console.WriteLine ( max);
Console.WriteLine (min);
Console.ReadKey ( );
}
}
}
params
params :当不知道传参的个数的时候,使用params 修饰一个数组参数传参
1.params不能与ref,out一起使用.
2.params修饰的数组形参,可以接受实参是数组,或者多个元素。
3.params修饰的数组形参在参数列表中还有其他参数的时候要放到最后。
4.一个方法中只允许存在一个params修饰的形参;
5.形参数组必须是一维数组.
例 :多元素和的计算
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
//params :当不知道传参的个数的时候,使用params 修饰一个数组参数传参
public class Math
{
public int Sum(params int [] num)
{
//用于接收总和
int h = 0;
foreach (int n in num)
{
h += n;
}
return h;
}
}
class Program
{
static void Main(string[] args)
{
Math m = new Math ( );
//方法中的实参可以是多个元素,也可以是单个数组
int a = m.Sum (4,5,8,9,6 );
Console.WriteLine ( a);
Console.ReadKey ( );
}
}
}