【发布时间】:2018-06-26 21:06:07
【问题描述】:
我正在浏览一些使用 C# 7 的新功能并使用 ref locals & return 功能的代码。
对于value-types 来说,ref 局部变量获取一个引用(对实际存储)并更新它会更新原始项目的值,这似乎很简单。
稍微解释一下将有助于理解在 reference-types 的 ref locals 的情况下内存引用是如何工作的。我指的是下面代码的最后一行:
// A simple class
public class CoolClass
{
public string Name { get; set; }
public int Id { get; set; }
public CoolClass(string name, int id) => (Name, Id) = (name, id);
}
//Dummy method that returns first element with Id > 100
public CoolClass GetSpecialItem_Old(CoolClass[] arr)
{
for (int i = 0; i < arr.Length; i++)
if (arr[i].Id > 100)
{
return arr[i];
}
throw new Exception("Not found");
}
//Same as the other one, but returns by ref C# 7
public ref CoolClass GetSpecialItem_New(CoolClass[] arr)
{
for (int i = 0; i < arr.Length; i++)
if (arr[i].Id > 100)
{
return ref arr[i];
}
throw new Exception("Not found");
}
public void TestMethod()
{
var arr = new CoolClass[]
{
new CoolClass("A", 10),
new CoolClass("B", 101),
new CoolClass("C", 11)
};
var byVal = GetSpecialItem_Old(arr); //gets back arr[1]
byVal.Name = "byVal"; //arr[1] = { "byVal", 101 }
byVal = new CoolClass("newByVal", 25); //arr[1] = { "byVal", 101 }
ref var byRef = ref GetSpecialItem_New(arr); //gets back arr[1]
byRef.Name = "byRef"; //arr[1] = { "byRef", 101 }
//Here it has a different behaviour
byRef = new CoolClass("newByRef", 50); //arr[1] = { "newByRef", 50 }
}
【问题讨论】:
-
ref var byRef与arr[1]的引用基本相同,所以如果您byRef = new ...您“实际上”在后台执行arr[1] = new ...。
标签: c# .net clr pass-by-reference c#-7.0