📜  C#| Copy()方法

📅  最后修改于: 2021-05-29 20:14:45             🧑  作者: Mango

在C#中,Copy()是一个字符串方法。它用于创建一个新的String实例,该实例的值与指定的String相同。 Copy()方法返回一个String对象,该对象与原始字符串相同,但表示不同的对象引用。要检查其引用,请使用赋值操作,该操作将现有的字符串引用分配给其他对象变量。

句法:

public static string Copy(string str)

说明:此方法接受单个参数str,该参数是要复制的原始字符串。然后返回字符串值,该字符串值是与str相同的新字符串。 Copy()方法的类型为System.String

演示Copy()方法的示例程序

// C# program to demonstrate the 
// use of Copy() method
using System;
class Program {
      
    static void cpymethod()
    {
        string str1 = "GeeksforGeeks";
        string str2 = "GFG";
        Console.WriteLine("Original Strings are str1 = "
            + "'{0}' and str2='{1}'", str1, str2);
                  
        Console.WriteLine("");
  
        Console.WriteLine("After Copy method");
        Console.WriteLine("");
  
        // using the Copy method
        // to copy the value of str1 
        // into str2
        str2 = String.Copy(str1);
  
        Console.WriteLine("Strings are str1 = "
        +"'{0}' and str2='{1}'", str1, str2);
  
        // check the objects reference equal or not
        Console.WriteLine("ReferenceEquals: {0}",
            Object.ReferenceEquals(str1, str2));
  
        // check the objects are equal or not
        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));
        Console.WriteLine("");
  
        Console.WriteLine("After Assignment");
        Console.WriteLine("");
  
        // to str1 object reference assign to str2
        str2 = str1;
  
        Console.WriteLine("Strings are str1 = '{0}' "
                    +"and str2 = '{1}'", str1, str2);
  
        // check the objects reference equal or not
        Console.WriteLine("ReferenceEquals: {0}", 
            Object.ReferenceEquals(str1, str2));
  
        // check the objects are equal or not
        Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));
  
    }
      
    // Main Method
    public static void Main()
    {
          
        // calling method
        cpymethod();
    }
}
输出:
Original Strings are str1 = 'GeeksforGeeks' and str2='GFG'

After Copy method

Strings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'
ReferenceEquals: False
Equals: True

After Assignment

Strings are str1 = 'GeeksforGeeks' and str2 = 'GeeksforGeeks'
ReferenceEquals: True
Equals: True

参考: https : //msdn.microsoft.com/en-us/library/system。字符串.copy