[英]Memory allocation under Methods in C# .Net
我仍在學習 C# 並且我在理解方法中的內存分配方面遇到了困難。 讓我們想象一下我得到了一些引用對象的情況,並且在我分配現有對象的方法中,將在內存中做什么?
我發現每個對象的實例方法是否在內存中重復? 但在我描述的情況下,對我來說並不是那么清楚。 任何其他參考將不勝感激。
public class ClassToBeAssigned : IClassToBeAssigned {}
public interface IClassToBeAssigned{}
public class AllocatingClass
{
private ClassToBeAssigned testAssigment;
// Just as example
void Main()
{
// new allocation in memory
testAssigment = new ClassToBeAssigned();
Assign(testAssigment);
}
// create here copy of context by assigned
void Assign(IClassToBeAssigned assigned)
{
// What will happend now if there are 4x method calls ?
DoSomething(assigned);
DoSomething(assigned);
DoSomething(assigned);
DoSomething(assigned);
}
void DoSomething(IClassToBeAssigned assignIt)
{
// What is happening here in memory allocation for that reference each call ?
IClassToBeAssigned dealWithIt = assignIt;
}
}
我只是對那里發生的事情有點困惑,我也找到了很多信息,但沒有針對這個特定問題。
分配引用不會在 C# 中創建副本。 您只需在Main
創建一個新實例,因此只有一個ClassToBeAssigned
實例。
值類型除外; 這些需要特別照顧。 如果ClassToBeAssigned
是struct
而不是class
,則每次調用Assign(testAssignment);
實際上會創建一個新實例,它是testAssignment
的副本。 請注意,即使在這種情況下, DoSomething(assignment);
不會產生新的副本。 如果您想了解有關此主題的更多信息,請閱讀 C# 中的拳擊。
至於DoSomething
,它絕對什么都不做,所以不清楚你會在那里發生什么:)
DoSomething
會從堆棧中為dealWithIt
變量分配一些字節,因此根據系統,它會分配 32 位或 64 位,因為dealWithIt
只是一個引用。
來自assignIt
的引用將被復制到分配的內存中,然后立即再次釋放,因為該方法已完成並且堆棧移回前一個方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.