📅  最后修改于: 2020-11-01 03:09:19             🧑  作者: Mango
C#ref关键字允许方法返回引用而不是值。在C#以前的版本中,方法只能返回值。
包含返回的引用(称为ref本地)的变量。
返回引用的方法具有下面列出的某些限制。
让我们来看一个例子。
using System;
namespace CSharpFeatures
{
class RefReturnsExample
{
public static void Main(string[] args)
{
string[] students = { "Rahul", "John", "Mayank", "Irfan" };
// Calling a method that returns a reference
ref string student = ref FindStudent(students, "John");
Console.WriteLine(student);
}
// A method that returns a ref type
static ref string FindStudent(string[] students, string student)
{
for (int i = 0; i < students.Length; i++)
{
if (students[i].Equals(student))
{
return ref students[i];
}
}
throw new Exception("Student not found");
}
}
}
输出:
John
Ref local是一个变量,用于存储方法返回的引用。让我们来看一个例子。
using System;
namespace CSharpFeatures
{
class RefReturnsExample
{
public static void Main(string[] args)
{
string[] students = { "Rahul", "John", "Mayank", "Irfan"};
Console.WriteLine("Array: [" + string.Join(",",students)+"]");
// Creating local reference
ref string student = ref students[3];
student = "Peter"; // It will change array value at third index
Console.WriteLine("Updated array: ["+string.Join(",",students)+"]");
}
}
}
输出:
Array: [Rahul,John,Mayank,Irfan]
Updated array: [Rahul,John,Mayank,Peter]