分配在堆上还是栈上?

Allocated on the heap or the stack?

我最近问了一个关于 WhosebugExeptions 的问题,解释非常有帮助!
但是,我写了一个方法,试图弄清楚T cached分配在哪里(heap/stack):

private Dictionary<Type, Component> _cachedComponents = new Dictionary<Type, Component>();

public T GetCachedComponent<T>() where T : Component {
   //Not yet sure if the next line works or throws an exception -> just ignore it
    if(_cachedComponents[typeof(T)] != null) {
        return (T)_cachedComponents[typeof(T)]
    } else {
        T cached = this.GetComponent<T>();
        _cachedComponents.Add(typeof(T), cached);
        return cached;
    }
}
  1. 因为 T cached 是在方法内部声明的,我假设它是在堆栈上分配的,对吗?
  2. 但是引用被添加到字典中,应该分配在堆上,对吧?
  3. 方法returns之后的堆栈是"cleared",对吧?
  4. 但是 T cached 会怎样?
    它会被移动到堆中吗?
    (因为堆栈不再"carry the data"但字典仍然保留引用)

Since T cached is declared inside the method I assume it is allocated on the stack, right?

T 在方法中分配不会影响它在堆或堆栈上。决定是前者还是后者,看这个是引用类型还是值类型。

But the reference is then added to the dictionary, wich should be allocated on the heap, right?

一旦将引用添加到 Dictionary<TKey, TValue>,键将存储在字典中,字典是在堆上分配的,因为它是引用类型。

The stack is "cleared" after the method returns, right?

堆栈在方法returns后被清除。

But what happens to T cached? Is it going to be moved to the heap?

如果 T 缓存在字典中,那么它已经分配在堆上。

总的来说,我假设你问这些问题是为了了解常识。你不应该太担心这个,因为我在这里写的是一个实现细节,可能会发生变化。