html代码hr表示,网站关键词排名优化系统,网站制作软件平台,宁夏网站建设多少钱函数传递参数
在C#中函数传递的参数#xff0c;函数内有操作改变其值#xff0c;并不会改变函数外参数对应变量的值#xff0c;可见如下实例#xff1a;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading…函数传递参数
在C#中函数传递的参数函数内有操作改变其值并不会改变函数外参数对应变量的值可见如下实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace code
{class Program{static void Main(string[] args){int a 10;Console.WriteLine(函数外 a);add(a);Console.WriteLine(函数外 a);Console.ReadKey();}static void add(int a){Console.WriteLine(函数内: a);a 10;Console.WriteLine(函数内: a);return;}}
}
输出结果 函数外10 函数内:10 函数内:20 函数外10 可见实际函数内对a进行10操作后函数外再输出a值并没有发生变化。由此成功印证函数内操作不会影响函数外变量值的结论。
关键字ref
一、作用
将变量本身传入函数使函数内对变量的操作可以影响函数外变量值。
注意此时变量在函数外必须赋值。
二、语法
在声明函数与使用函数时均需要在形参与实参前加上ref关键字。
上面的实例修改后如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace code
{class Program{static void Main(string[] args){int a 10;Console.WriteLine(函数外 a);add(ref a); //添加ref关键字Console.WriteLine(函数外 a);Console.ReadKey();}static void add(ref int a) //添加ref关键字{Console.WriteLine(函数内: a);a 10;Console.WriteLine(函数内: a);return;}}
}
此时程序输出结果 函数外10 函数内:10 函数内:20 函数外20 可见在修改后的本实例中函数内对a的修改操作影响了函数外变量a的值。
三、分析
调用函数时传递参数是将变量值传递到栈空间中而使用了ref关键字则是将变量的地址值传递到栈空间即“引用传递”。函数通过地址获得变量实际存储位置直接对变量进行操作从而实现函数内操作影响函数外变量值。
关键字out
一、作用
当希望函数返回多个不同类型返回值时通过out关键字可以实现。
注意相关变量函数外可以不赋值但函数内必须赋值。
二、语法
在声明函数与使用函数时均需要在形参与实参前加上out关键字。
例如希望获得两个int型数据的最大值、最小值、和、商其中商需要为double型数据。以下实例可实现该功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace code
{class Program{static void Main(string[] args){int a 10, b 3;int _max, _min, _sum;double _quo;func(a, b, out _max, out _min, out _sum, out _quo);Console.WriteLine(max{0} min{1} sum{2} quo{3}, _max, _min, _sum, _quo);Console.ReadKey();}static void func(int a,int b,out int _max,out int _min,out int _sum,out double _quo){_max (a b) ? a : b;_min (a b) ? a : b;_sum a b;_quo (double)(a / (double)(b));return;}}
}
输出结果如下 max10 min3 sum13 quo3.33333333333333 在Main函数中实际并没有对几个下划线为起始的变量名赋值但最后输出时几个变量都输出了通过函数func获得的对应值。可见函数通过out关键字以类似的形式传递了多个返回值。