public ref int GetData()
{
var myDataStructure = new MyDataStructure();
return ref myDataStructure.Data;
}
public class MyDataStructure
{
private int _data;
public ref int Data => ref _data;
}
这使用了新的 C#7 引用返回功能。 GetData() 返回后,内存中保存了什么?完整的 MyDataStructure 实例?还是只有整数?
如果 MyDataStructure 实例保存在内存中,因为有人持有对该实例的某个字段的引用,那么在这个例子中为什么不能保存在内存中:
public ref string GetString()
{
string s = "a";
return ref s;
}
最佳答案
After GetData() returns, what is kept in memory? The complete MyDataStructure instance? Or only the integer?
MyDataStructure
是。它存在于堆中,并且您可以引用其中的一个字段。why can't s be kept in memory in this example
因为虽然它指向的堆上的字符串存在于堆上,
s
本身是不在堆上的本地。作为本地,在方法完成后它就不再存在了。
关于ref - C#7 引用返回 : what stays in memory: the class instance or the ref returned property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841271/