在C#.Net中的方法下的内存分配

问题描述 投票:0回答:1

根据报价

..“不问” ..]的愚蠢人

我仍在学习C#,在了解方法下的内存分配的情况下,我处于困境中。让我得到一些参考对象的图像情况,在我分配现有对象的方法下,将在内存中做什么?

我找到了Are instance methods duplicated in memory for each object?,但就我描述的情况而言,对我来说还不太清楚。对于任何其他参考,我将不胜感激。

    1| namespace MemoryAllocationUnderstanding
    2| {
    3|    public class ClassToBeAssigned : IClassToBeAssigned {}
    4|    public interface IClassToBeAssigned{}
    5| 
    6|    public class AllocatingClass
    7|    {
    8|        private ClassToBeAssigned testAssigment;
    9|        // Just as example
    10|         void Main()
    11|         {
    12|              // new allocation in memory
    13|              testAssigment = new ClassToBeAssigned();
    14|
    15|              Assign(testAssigment);
    16|         }
    17|         // create here copy of context by assigned
    18|         void Assign(IClassToBeAssigned assigned)
    19|         {
    20|              // What will happend now if there are 4x method calls ?
    21|              DoSomething(assigned);
    22|              DoSomething(assigned);
    23|              DoSomething(assigned);
    24|              DoSomething(assigned);
    25|         }
    26|         void DoSomething(IClassToBeAssigned assignIt)
    27|         {
    28|              // What is happening here in memory allocation for that reference each call ?
    29|             IClassToBeAssigned dealWithIt = assignIt;
    30|         }
    31|     }
    32|  }

我只是对那里发生的事情感到困惑,我也发现了很多信息,但是对于这个特定问题却一无所获。

根据引述..“一个不问的愚蠢的人。”我仍在学习C#,并且在了解方法下的内存分配的情况下处于困境。让我得到的图像情况...

c# .net memory-management allocation
1个回答
0
投票

分配参考不会在C#中创建副本。您仅在Main中创建一个新实例,因此ClassToBeAssigned只有一个实例。

© www.soinside.com 2019 - 2024. All rights reserved.