本文介绍了通过引用传递对象时存储在堆栈中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过引用调用对象时,什么被压入堆栈。请考虑以下代码,

    

   使用系统;

    class em

    {

       public int i = 0;

    }
   课程计划

    {

        public void method(int a,ref int b,em c,ref em d)

        {

             //实施

        }
        static public void Main()

        {

             int i;

             int j;

             em e1 = new em();

             em e2 = new em();

             i = 9;

             j = 10;

            节目p =新节目();

             p.method(i,ref j,e1,ref e2);

        }
   当e1通过时,对象的引用作为参数传递,但是当e2通过引用传递到堆栈上时,在此代码中为
,即什么作为参数传递给方法?

what gets pushed onto the stack when an object is called by reference. Consider below code,
    
    using System;
    class em
    {
       public int i=0;
    }
    class program
    {
        public void method(int a, ref int b, em c, ref em d)
        {
             //implementation
        }
        static public void Main()
        {
             int i;
             int j;
             em e1 = new em();
             em e2 = new em();
             i=9;
             j=10;
             Program p=new Program();
             p.method(i,ref j,e1,ref e2);
        }
    }
when e1 passed ,the reference of the object is passed as the argument but
in this code when e2 is passed by reference what is pushed onto the stack i.e., what is passed as the argument to the method ?

推荐答案

请注意,参数实际上只是美化的局部变量,它们都会同时分配,因此应用的所有内容都适用本地人使用参数。

Note that parameters are really just glorified local variables and they all get allocated at the same time so everything that applies to locals works with parameters.

当e2通过引用传递时,因为它是一个ref参数,所以编译器只存储一个引用(指针)。但请注意,这是大多数语言的实现细节。如果他们愿意,语言可以决定在序言期间通过值方法
进行复制,然后在功能结尾期间将(修改的)值复制回原始参数。但与简单地直接传递它相比,这是低效的,因此为什么大多数语言(我知道)都这样做。

When e2 is passed by reference, since it is a ref parameter, then the compiler just stores a reference (pointer) to it. But note that this is an implementation detail in most languages. A language may, if they so choose, decide to do a copy by value approach during the prologue and then copy the (modified) value back to the original argument during function epilogue. But this is inefficient compared to simply passing the reference to it directly hence why most languages (that I'm aware of) do it that way.


这篇关于通过引用传递对象时存储在堆栈中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 06:48