ภาพรวม
String.Copy(String str) สร้างสตริงใหม่ที่มีค่าเหมือนกันทุกประการ (deep copy สำหรับสตริง) คืนค่า string ใหม่
ตัวอย่างที่ 1: คัดลอกสตริง "Kevin" ไปตัวใหม่
using System;
public class Demo
{
static public void Main()
{
string str1 = "Kevin";
string str2 = String.Copy(str1);
Console.WriteLine("String1 = " + str1);
Console.WriteLine("String2 = " + str2);
}
}
ผลลัพธ์
String1 = Kevin String2 = Kevin
ตัวอย่างที่ 2: คัดลอกทับค่าสตริงเดิม
using System;
public class Demo
{
static public void Main()
{
string str1 = "Maisie";
string str2 = "Ryan";
Console.WriteLine("String1 (Before copying) = " + str1);
Console.WriteLine("String2 (Before copying) = " + str2);
str2 = String.Copy(str1);
Console.WriteLine("String1 = " + str1);
Console.WriteLine("String2 (Updated) = " + str2);
}
}
ผลลัพธ์
String1 (Before copying) = Maisie String2 (Before copying) = Ryan String1 = Maisie String2 (Updated) = Maisie
สรุป
String.Copy()สร้างอินสแตนซ์สตริงใหม่ ค่าตรงกันทุกตัวอักษร- สตริงใน C# เป็น immutable การกำหนดค่าใหม่จะสร้างอินสแตนซ์ใหม่เสมอ
- ต่างจากการกำหนด
str2 = str1ที่อ้างอิง instance เดียวกัน