无涯教程-C# - 按引用传递

28 阅读1分钟

C#提供ref关键字将参数作为引用类型传递。它将参数引用传递给函数,而不是原始值的副本。传递的值中的更改是永久性的,修改原始变量值。

C#引用调用示例

using System; namespace CallByReference { class Program { // 用户定义的函数 public void Show(ref int val) { val *= val; // Manipulating value Console.WriteLine("Value inside the show function "+val); // No return statement } static void Main(string[] args) { int val = 50; Program program = new Program(); // 创建对象 Console.WriteLine("Value before calling the function "+val); program.Show(ref val); // 通过引用来调用函数 Console.WriteLine("Value after calling the function " + val); } } }

输出:

Value before calling the function 50 Value inside the show function 2500 Value after calling the function 2500

参考链接

www.learnfk.com/csharp/c-sh…