ref - C#7 引用返回 : what stays in memory: the class instance or the ref returned property?

标签 ref c#-7.0

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/

相关文章:

c# - 属性中表达式体的已知问题?

C++ 引用字节数组

C# 'ref' 关键字,性能

c# - 带返回值的空合并运算符 (??)

c# - 在 ASP.NET Core Web API Controller 中使用 C# 7 元组

c# - 为什么在混合 C# ValueTuple 和动态时出现此编译器错误

C# 如何返回 null 或模型

c# - 如何在 lambda 表达式中传递 ref 参数? - 线程问题

c# - 在 C# 中创建动态字符串

pdf - 尝试理解 PDF 中交叉引用 (XRef) 流中的数据