C#中的ref关键字用于在方法之间传递值的引用或从方法返回值的引用。基本上,这意味着对引用传递的值所做的任何更改都将反映此更改,因为您正在修改地址中的值,而不仅仅是修改值。它可以在以下情况下实现:
- 通过引用将参数传递给方法。
- 定义方法签名以返回变量的引用。
- 将结构声明为引用结构
- 作为当地参考
示例1:在这里,我们定义了两个方法addValue和减去Value。方法addValue是仅修改其参数值的方法。因此,当将’a’的值作为参数传递给addValue后显示出来时,其值没有差别。而方法extractValue使用参数的引用,而关键字ref表示该引用。因此,当将’b’的值作为参数传递给减去值后显示时,您可以看到更改反映在其值中。在方法定义以及调用方法时必须使用ref关键字。
// C# program to illustrate the
// use of ref keyword
using System;
namespace ref_keyword {
class GFG {
// Main Method
static void Main(string[] args)
{
// Initialize a and b
int a = 10, b = 12;
// Display initial values
Console.WriteLine("Initial value of a is {0}", a);
Console.WriteLine("Initial value of b is {0}", b);
Console.WriteLine();
// Call addValue method by value
addValue(a);
// Display modified value of a
Console.WriteLine("Value of a after addition"+
" operation is {0}", a);
// Call subtractValue method by ref
subtractValue(ref b);
// Display modified value of b
Console.WriteLine("Value of b after "+
"subtration operation is {0}", b);
}
// Define addValue
// Parameters passed by value
public static void addValue(int a)
{
a += 10;
}
// Define subtractValue
// Parameters passed by ref
public static void subtractValue(ref int b)
{
b -= 5;
}
}
}
输出:
Initial value of a is 10
Initial value of b is 12
Value of a after addition operation is 10
Value of b after subtration operation is 7
示例2:您也可以将关键字ref与类的实例一起使用。在下面给出的程序中,我们有一个Complex类来表示复数。该类还包含一个update方法,该方法使用对象的引用并反映对象的实部和虚部的值中进行的更新。
// C# program to show the use of ref
// with an instance of a class
using System;
namespace class_ref {
class Complex {
private int real, img;
// Parameterize Constructor
public Complex(int r, int i)
{
real = r;
img = i;
}
// Method to get value of real
public int getRealValue()
{
return real;
}
// Method to get value of img
public int getImgValue()
{
return img;
}
// Method to update value of complex
// object Using reference of the object
public static void Update(ref Complex obj)
{
obj.real += 5;
obj.img += 5;
}
}
class GFG {
// Main Method
static void Main(string[] args)
{
// Declare Complex object
Complex C = new Complex(2, 4);
Console.WriteLine("Complex number C = " + C.getRealValue() +
" + i " + C.getImgValue());
// Call update method
// Pass ref of C
Complex.Update(ref C);
Console.WriteLine("After updating C");
Console.WriteLine("Complex number C = " + C.getRealValue() +
" + i " + C.getImgValue());
}
}
}
输出:
Complex number C = 2 + i 4
After updating C
Complex number C = 7 + i 9