Computer >> Máy Tính >  >> Lập trình >> C#

Sự khác biệt giữa phương thức String.Copy () và String.Clone () trong C # là gì?

Phương thức String.Copy () tạo một thể hiện mới của String. Điều này giống với chuỗi được chỉ định.

Sau đây là một ví dụ về phương thức Copy () -

Ví dụ

using System;
class Demo {
   static void Main(String[] args) {

      string str1 = "mark";
      string str2 = "marcus";

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);

      Console.WriteLine("After using String.Copy...");
      str2 = String.Copy(str1);

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
   }
}

Đầu ra

str1 = 'mark'
str2 = 'marcus'
After using String.Copy...
str1 = 'mark'
str2 = 'mark'

Phương thức String.Clone () trả về một tham chiếu đến thể hiện của String. Sau đây là một ví dụ về phương thức Clone () -

Ví dụ

using System;
class Demo {
   static void Main(String[] args) {
     
      string str1 = "amy";
      string str2 = "emma";

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);

      Console.WriteLine("After using String.Clone...");
      str2 = (String)str1.Clone();

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
   }
}

Đầu ra

str1 = 'amy'
str2 = 'emma'
After using String.Clone...
str1 = 'amy'
str2 = 'amy'