Value type and reference type problem

前端 未结 7 1462
花落未央
花落未央 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:31

    Rather than passing the references to the objects by value you need to pass them by reference. In other words, you need to pass a reference to the reference to the object.

    This is achieved using the ref keyword.

    E.g.

    private static void Swap(ref object First, ref object Second)
    {
      object temp = First;
      First = Second;
      Second = temp;
    }
    
    0 讨论(0)
提交回复
热议问题