Ref - Parameters - stack or heap

His only theoretical question, but I cannot get a good answer:

If you pass a parameter ref, the object itself is passed, not a copy.

Here's what bothers me: As far as I know, each method has its own stack of frames - memory that they cannot leave. That is, does this mean that the ref-Object is packed in a heap, and is there a link to this parameter, or does the method go to the stack of the calling method and work there?

Sorry if my question is confusing, I basically would like to know how the type of link is saved and what impact it has.

Edith: I think I did not understand. I understand the concept of values ​​and types of refence. To keep things simple, I'm trying to explain this simply with the value type of, say, Int:

Procedure 1 calls Prodecure 2, passing Int ByVal. This int has its own memory in Stack of Prodecure 2, which means that changing this value to P2 does not change the value in P1, since these 2 values ​​are stored on each stack once.

Now the same with byref: Prodecure 2 does not save a copy of Int, but has access to this value directly. There are (in my Oppinion) two possibilities to make this work:

  • Int is packed in a heap, and there are actually 2 pointers to this Int, but since it is now on the heap, cost changes are visible on both Prodecures.
  • P2 has access to the P1 stack, which I thought was impossible, as this would mean that the stack has not expired in Stone.

Does this mean that I understood what I mean?

+4
source share
2

, , . .

, , . , , . , , , .

+8

, Servy , , , ref . , .

, :

class Player
{
    public Player(int health)
    {
        Health = health;
    }
    public int Health { get; set; }
}

, :

static void Main(string[] args)
{
    Player player = new Player(100);
    Console.WriteLine(player.Health);

    ChangeHealth(player);
    Console.WriteLine(player.Health);
    ChangeHealthByRef(ref player);
    Console.WriteLine(player.Health);

    ChangePlayer(player);
    Console.WriteLine(player.Health);
    ChangePlayerByRef(ref player);
    Console.WriteLine(player.Health);
}

static void ChangeHealth(Player player)
{
    player.Health = 80;
}

static void ChangeHealthByRef(ref Player player)
{
    player.Health = 60;
}

static void ChangePlayer(Player player)
{
    player = new Player(40);
}

static void ChangePlayerByRef(ref Player player)
{
    player = new Player(20);
}

:

100
80
60
60
20

ChangeHealth Health player. ChangeHealthByRef Health player. , , , player, , ChangeHealth, .

, , , :

ChangePlayer player, . , (.. Health still = 60). ChangePlayerByRef player, , , (.. Health= 20).

+1

Source: https://habr.com/ru/post/1531338/


All Articles