Value type and reference type problem

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

    You need to pass by reference.

    Here's some extra info on pass-by-refence, pass-by-value: http://www.yoda.arachsys.com/csharp/parameters.html, try this:

    void Main()
    {
     object First = 5;
     object Second = 10;
    
      Swap(ref First, ref Second);
      //If I display results it displays as 
      //Value of First as 5 and Second as 10
    }
    
    
    private static void Swap(ref object First, ref object Second)
    {
      object temp = First;
      First = Second;
      Second = temp;
    }
    

提交回复
热议问题