Shallow copy:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Vehicle vehicleOne = new Vehicle(); | |
Vehicle vehicleTwo = new Vehicle(); | |
vehicleOne = vehicleTwo; |
There are two ways of doing this.
1. Use the copy constructor (a good practice)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Vehicle | |
{ | |
// Copy constructor. | |
public Vehicle (Vehicle previousVehicle) | |
{ | |
Name = previousVehicle.Name; | |
Year = previousVehicle.Year; | |
} | |
//// Alternate copy constructor calls the instance constructor. | |
//public Vehicle (Vehicle previous Vehicle) | |
// : this(previousVehicle.Name, previousVehicle.Year) | |
//{ | |
//} | |
// Instance constructor. | |
public Vehicle(string name, int year) | |
{ | |
Name = name; | |
Year = year; | |
} | |
public int Year { get; set; } | |
public string Name { get; set; } | |
} | |
// Create a Vehicle object by using the instance constructor. | |
Vehicle vehicle1 = new Vehicle("Toyota", 2014); | |
// Create another Vehicle object, copying vehicle1. | |
Vehicle vehicle2 = new Vehicle(person1); |
Manual way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Vehicle: ICloneable | |
{ | |
public string Name; | |
public int Year; | |
public object Clone() | |
{ | |
Vehicle v = new Vehicle (); | |
v.Name = this.Name; | |
v.Year = this.Year; | |
return v; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Vehicle : ICloneable | |
{ | |
public string Name; | |
public int Year; | |
public object Clone() | |
{ | |
return this.MemberwiseClone(); | |
} | |
} | |
//how to use | |
Vehicle toyota = new Vehicle(); | |
Vehicle toyotaClone = (Vehicle)toyota.Clone(); |
No comments:
Post a Comment