我的印象是在C#中,struct元素在堆栈上分配,因此从创建它们的方法返回时会消失.但是如果我将struct-values放在一个列表中并返回它会发生什么?元素幸存下来.是否有时在堆上分配struct实例?
internal struct Stru
{
public int i;
}
internal class StruTry
{
public List<Stru> Get(int max)
{
var l = new List<Stru>();
for (int i = 0; i < max; i++)
l.Add(new Stru {i=i});
return l;
}
}
Run Code Online (Sandbox Code Playgroud)
代码打印0,1,2
[Test]
public void T()
{
var ll = new StruTry().Get(3);
foreach (var stru in ll)
Console.WriteLine("* "+ stru.i);
}
Run Code Online (Sandbox Code Playgroud) 我有点困惑的是,在C#中只有引用类型被垃圾收集.这意味着GC只选择内存解除分配的引用类型.那么值类型会发生什么呢?因为它们也会占用堆栈上的内存?