Код: Выделить всё
private struct NormalStruct
{
public bool MyBool;
}
...
public void TestMethod()
{
long valA = GC.GetAllocatedBytesForCurrentThread();
NormalStruct normalStruct = new();
long valB = GC.GetAllocatedBytesForCurrentThread();
long allocatedByteCount = valB - valA;
// No allocation on the heap
Assert.IsTrue(allocatedByteCount == 0);
unsafe
{
// No warnings
NormalStruct* ptr = &normalStruct;
}
}
Поэтому в этом случае я думаю, что NormalStruct избежит сборки мусора
А теперь рассмотрим другой пример
Код: Выделить всё
private struct ManagedStruct
{
public bool MyBool;
// Introducing a string in the struct to make it managed
public string MyString;
}
...
public void TestMethod()
{
long valA = GC.GetAllocatedBytesForCurrentThread();
ManagedStruct managedStruct = new();
long valB = GC.GetAllocatedBytesForCurrentThread();
long allocatedByteCount = valB - valA;
// Still no allocation on the heap
Assert.IsTrue(allocatedByteCount == 0);
unsafe
{
// Here a warning says that managedStruct is managed
// Warning CS8500: This takes the address of, gets the size of, or declares a pointer to a managed type
ManagedStruct * ptr = &managedStruct;
}
}
Я считал само собой разумеющимся, что каждый управляемый объект размещается в куче, оказывается, я ошибался?
GC.GetAllocatedBytesForCurrentThread измеряет распределение в управляемой куче.
Почему здесь ничего не отображается, означает ли это, что ManagedStruct выделен в стеке?
И вопрос, на который мне действительно нужен ответ: попадут ли экземпляры ManagedStruct в сборщик мусора?
Подробнее здесь: https://stackoverflow.com/questions/792 ... -collected