在C#中 ref关键字用于通过引用调用。
它用于通过引用传递参数,如果对该方法对传递参数进行了任何更改,则更改将在原始变量中反映为参数传递。
它是使用的两个地方;当我们声明方法时以及拨打该方法时。
以下示例将解释我们如何在C#中使用REF参数。
在此示例中,我们创建了一个函数(方形)并通过它的参考参数,现在我们在调用该功能之前查看该值并在我们调用函数后。
C#中的ref参数示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class RefExample
{
public void square(ref int x)
{
x = x * x;
}
}
class Program
{
static void Main(string[] args)
{
RefExample tr = new RefExample();
int a = 3;
Console.WriteLine("调用前a的值: " + a);
tr.square(ref a);
Console.WriteLine("调用后a的值: " + a);
Console.ReadLine();
}
}
日期:2020-04-11 23:03:53 来源:oir作者:oir
