【问题标题】:Memory allocation under Methods in C# .NetC# .Net 中方法下的内存分配
【发布时间】:2020-03-06 13:53:33
【问题描述】:

我仍在学习 C#,并且在理解方法中的内存分配方面遇到困难。 让我们想象一下我得到一些引用对象的情况,并且在我分配现有对象的方法中,将在内存中做什么?

我找到了Are instance methods duplicated in memory for each object?,但如果我描述的话,我不太清楚。 任何其他参考将不胜感激。

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# .net memory-management allocation


    【解决方案1】:

    分配引用不会在 C# 中创建副本。您只在Main 中创建了一个新实例,因此ClassToBeAssigned 的实例只有一个。

    值类型除外;这些需要特别注意。如果ClassToBeAssignedstruct 而不是class,则每次调用Assign(testAssignment); 实际上都会创建一个新实例,它是testAssignment 的副本。请注意,即使在这种情况下,DoSomething(assignment); 也不会生成新副本。如果您想了解有关此主题的更多信息,请阅读 C# 中的拳击。

    至于DoSomething,它完全没有任何作用,所以不清楚你期望在那里发生什么:)

    【讨论】:

      【解决方案2】:

      DoSomething 将从堆栈中为 dealWithIt 变量分配一些字节,因此取决于系统分配的 32 位或 64 位,因为 dealWithIt 只是一个参考。
      来自assignIt 的引用随后将被复制到分配的内存中,然后立即再次释放,因为该方法完成并且堆栈移回前一个方法。

      【讨论】:

        猜你喜欢
        • 2017-06-10
        • 1970-01-01
        • 1970-01-01
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多