Csharp/CSharp Tutorial/struct/struct copy

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Copy a struct.

<source lang="csharp">using System;

struct MyStruct {

 public int x; 

}

class MainClass {

 public static void Main() { 
   MyStruct a; 
   MyStruct b; 

   a.x = 10; 
   b.x = 20; 

   Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 

   a = b; 
   b.x = 30; 

   Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); 
 } 

}</source>

a.x 10, b.x 20
a.x 20, b.x 30

Copy a struct instance by assignment

<source lang="csharp">using System;

   public struct Point
   {
       public int x;
       public int y;
       public Point( int x, int y )
       {
           this.x = x;
           this.y = y;
       }
       public void Print()
       {
           System.Console.WriteLine( "x = {0}, y = {1}", x, y );
       }
   }
   class MainClass
   {
       static void Main(string[] args)
       {
           Point p = new Point( 3, 4 );
           Point q = p;    // takes a copy
           q.x = 5;        // only changes q not p
           p.Print();      // so we still see x = 3, y = 4
       }
   }</source>
x = 3, y = 4