Ob’ektlarni nusxalash. ICloneable interfeysi
Sinflar bog‘lovchi turlarni taqdim etayotgani uchun, ulardan foydalanishga ayrim cheklovlar qo‘yadi. Xususan:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Program
{
static void Main(string[] args)
{
Person p1 = new Person { Name="Tom", Age = 23 };
Person p2 = p1;
p2.Name = "Alice";
Console.WriteLine(p1.Name); // Alice
Console.Read();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
|
Ushbu holda p1 va p2 ob’ektlari ham bir xil ob’ektni ro‘yxatda ko‘rsatadi, shuning uchun p2 o‘zgaruvchisidagi xossalarning o‘zgartirilishi p1 o‘zgaruvchisiga ham ta’sir ko‘rsatadi.
p2 o‘zgaruvchisi yangi ob’ektni ko‘rsatishi uchun, biroq p1 qiymatlari bilan, ICloneable interfeysini amalga oshirish orqali klonlashni amalga oshirishimiz mumkin:
public interface ICloneable
{
object Clone();
}
Person sinfida interfeysni amalga oshirish quyidagicha koʻrinishi mumkin:
class Person : ICloneable
{
public string Name { get; set; }
public int Age { get; set; }
public object Clone()
{
return new Person { Name = this.Name, Age = this.Age };
}
}
Foydalanish:
class Program
{
static void Main(string[] args)
{
Person p1 = new Person { Name="Tom", Age = 23 };
Person p2 = (Person)p1.Clone();
p2.Name = "Alice";
Console.WriteLine(p1.Name); // Tom
Console.Read();
}
}
Endilikda hamma nusxa olinmoqda, p2 xossalaridagi o‘zgarishlar p1 xossalariga ta’sir ko‘rsatmaydi.
Nusxa olish kodini qisqartirish uchun ob’ektning nusxasini qaytaradigan maxsus MemberwiseClone () usulidan foydalanishimiz mumkin:
Ushbu usul yuqori (chuqur bo‘lmagan) nusxa olishni amalga oshiradi. Biroq ushbu nusxa olish etarli bo‘lmasligi mumkin. Masalan, Person sinfida Company:
class Person : ICloneable
{
public string Name { get; set; }
public int Age { get; set; }
public Company Work { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
class Company
{
public string Name { get; set; }
}
Ushbu holda nusxa olishda yangi nusxa ham shunday Company ob’ektini ko‘rsatadi:
Person p1 = new Person { Name="Tom", Age = 23, Work= new Company { Name = "Microsoft" } };
Person p2 = (Person)p1.Clone();
p2.Work.Name = "Google";
p2.Name = "Alice";
Console.WriteLine(p1.Name); // Tom
Console.WriteLine(p1.Work.Name); // Google - lekin Microsoft bo’lishi kerak
Sirtdan nusxa olish faqatgina primitiv turlarni ifodalovchi xossalar uchun ishlaydi, lekin murakkab obʼyektlar uchun emas. Bunda quyidagilar chuqur nusxa olinishi kerak:.
class Person : ICloneable
{
public string Name { get; set; }
public int Age { get; set; }
public Company Work { get; set; }
public object Clone()
{
Company company = new Company { Name = this.Work.Name };
return new Person
{
Name = this.Name,
Age = this.Age,
Work = company
};
}
}
class Company
{
public string Name { get; set; }
}
Do'stlaringiz bilan baham: |