使用new运算符创建类的实例时,将在堆上分配内存.当您使用new运算符创建结构的实例时,在堆上还是堆栈上分配内存?
我的印象是在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) 如果struct包含DateTime字段,为什么LayoutKind.Sequential的工作方式不同?
请考虑以下代码(必须使用"unsafe"启用的编译器应用程序):
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication3
{
static class Program
{
static void Main()
{
Inner test = new Inner();
unsafe
{
Console.WriteLine("Address of struct = " + ((int)&test).ToString("X"));
Console.WriteLine("Address of First = " + ((int)&test.First).ToString("X"));
Console.WriteLine("Address of NotFirst = " + ((int)&test.NotFirst).ToString("X"));
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct Inner
{
public byte First;
public double NotFirst;
public DateTime WTF;
}
}
Run Code Online (Sandbox Code Playgroud)
现在如果我运行上面的代码,我得到类似于以下的输出:
struct = 40F2CC的
地址First = 40F2D4的
地址NotFirst的地址= 40F2CC
注意,First的地址与struct的地址不同; 然而,NotFirst的地址是一样的结构的地址.
现在注释掉结构中的"DateTime WTF"字段,然后再次运行它.这一次,我得到的输出类似于:
struct …