Value type and reference type problem

前端 未结 7 1464
花落未央
花落未央 2021-01-21 04:59

Hi I\'m trying to do a simple swap of two objects.My code is

void Main()
{
  object First = 5;
  object Second = 10;

  Swap(First, Second);
  //If I display res         


        
7条回答
  •  野的像风
    2021-01-21 05:16

    The object pointed to by the parameters inside the Swap method are references to the First and Second objects inside Main, but the parameters themselves are local to the Swap method.

    So if you inside Swap had written First = 1; Second = 2;, you would have seen the change in the objects inside Main. However, you only change what the paremeters to Swap point to (by assigning them to another object), and do not change the objects at all. The same would be true if you tried setting the objects to null inside the Swap method.

提交回复
热议问题