ref
2024-10-12 07:45:46
ref: 当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。
例如:
class RefExample
{
//使用ref返回的函数
static void Method(ref int i)
{
i = 44;
}
//普通函数
static int Sum(int j)
{
j = j + 1;
return j;
}
static void Main()
{
//使用ref返回的函数
int val = 0;
Method(ref val); //当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。
Console.WriteLine(val);//44
//Console.WriteLine(Method(ref val)); 错误:Method是无返回值(void)函数
//普通函数
int x = 0;
Sum(x);
Console.WriteLine(x);//0
Console.WriteLine(Sum(x)); //1
Console.ReadKey();
}
}
ref参数通俗解释:
能够将一个变量带入一个方法中进行改变,改变完成后,再讲改变后的值带出方法。
ref参数要求在方法外必须为其赋值,而方法内可以不赋值。
练习
class Program
{
static void Main(string[] args)
{
//使用方法来交换两个int类型的变量
int n1 = 10;
int n2 = 20; Test(ref n1, ref n2);
Console.WriteLine(n1);
Console.WriteLine(n2);
Console.ReadKey(); } public static void Test(ref int n1, ref int n2)
{
int temp = n1;
n1 = n2;
n2 = temp;
}
}
最新文章
- C/C++内存泄漏及检测
- 完整部署CentOS7.2+OpenStack+kvm 云平台环境(4)--用OZ工具制作openstack镜像
- validate表单验证插件
- Total Commander解压位置
- install intel c/c++ compiler
- Disable the screen switching about VI
- 如何用expdp、impdp按表空间导出、导入?
- Shell重定向&>;file、2>;&;1、1>;&;2的区别
- webrtc之视频捕获模块--video_capture
- 2016 ccpc 杭州赛区的总结
- servlet以及HTML中路径问题
- Python类中的self到底是干啥的
- iOS开源加密相册Agony的实现(六)
- python3导入sqlite3报错
- day60 pymysql
- 学习笔记TF043:TF.Learn 机器学习Estimator、DataFrame、监督器Monitors
- MySQL中校验规则(collation)的选取对实际数据筛选的影响
- iOS.Notification.Bar.Color
- EF CodeFirst(四) 关系
- mfc CSpinButton