C# 中的 ref 和 out 的意义和使用方法
2023-09-14 09:02:24 时间
向方法传递一个实参时,对应的形参会用实参的一个副本来初始化,不管形参是值类型(例如 int),可空类型(int?),还是引用类型,这一点都是成立的。也就是随便在方法内部进行什么修改,都不会影响实参的值。例如,对于引用类型,方法的改变,只是会改变引用的数据,但实参本身并没有变化,它仍然引用同一个对象。
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ref_out { class Program { static void Main(string[] args) { int i = 8; Console.WriteLine(i); DoIncrease(i); Console.WriteLine(i); } static void DoIncrease(int a) { a++; } } }
运行结果如下:
若使用 ref 关键字,向形参应用的任何操作都同样应用于实参,因为形参和实参引用的是同一个对象。
PS:实参和形参都必须附加 ref 关键字做为前缀。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ref_out { class Program { static void Main(string[] args) { int i = 8; Console.WriteLine(i); // 8 DoIncrease(ref i); // 实参前也必须加 ref Console.WriteLine(i); // 9 // ref 关键字使对形参的动作也应用于实参 } static void DoIncrease(ref int a) // 形参前必须加 ref { a++; } } }
运行结果如下
ref 实参使用前也必须初始化,否则不能通过编译。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ref_out { class Program { static void Main(string[] args) { int i; // ref 实参没有初始化,所以程序不能通过编译 Console.WriteLine(i); DoIncrease(ref i); Console.WriteLine(i); } static void DoIncrease(ref int a) { a++; } } }
有时我们希望由方法本身来初始化参数,这时可以使用 out 参数。
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ref_out { class Program { static void Main(string[] args) { int i; // 没有初始化 //Console.WriteLine(i); // 此处 i 未初始化,编译错误 DoIncrease(out i); // 用方法来给实参赋初值 Console.WriteLine(i); } static void DoIncrease(out int a) { a = 8; // 在方法中进行初始化 a++; // a = 9 } } }
相关文章
- c# mysql executenonquery_C#与数据库访问技术之ExecuteNonQuery方法
- c/s架构开发-C#下基于C/S架构的任务管理系统——开发安装
- C#11 新特性整理
- 【愚公系列】2023年01月 .NET/C#知识点-List对象去重的方法总结
- asp.net(c#)两种随机数的算法,可用抽考题
- asp.netc#抓取页面信息方法介绍
- C#中HashTable的定义与使用方法
- C#SetWindowPos窗口置顶使用说明
- C#SendKeys使用方法介绍
- asp.netC#实现下载文件的六种方法实例
- C#StringReplace高效的实例方法
- c#解压文件的实例方法
- C#实现抓取网站页面内容的实例方法
- C#波形图控件制作示例程序
- C#三种序列化方法分享
- C#实现漂亮的数字时钟效果
- C#实现跨线程操作控件方法
- C#调用sql2000存储过程方法小结
- Redis总结笔记(二):C#连接Redis简单例子
- C#(WinForm)ComboBox和ListBox添加项及设置默认选择项
- C#实现把dgv里的数据完整的复制到一张内存表的方法
- C#实现WinForm捕获最小化事件的方法
- C#逐行读取txt文件的方法