String.Copy(String) 方法

定义

警告

此 API 现已过时。

创建一个与指定的 String 具有相同值的 String 的新实例。Creates a new instance of String with the same value as a specified String.

public:
 static System::String ^ Copy(System::String ^ str);
[System.Obsolete("This API should not be used to create mutable strings. See https://go.microsoft.com/fwlink/?linkid=2084035 for alternatives.")]
public static string Copy (string str);
static member Copy : string -> string
Public Shared Function Copy (str As String) As String

参数

str
String

要复制的字符串。The string to copy.

返回

值与 str 相同的新字符串。A new string with the same value as str.

属性

异常

strnullstr is null.

注解

Copy 方法返回一个 String 对象,该对象与原始字符串具有相同的值,但表示不同的对象引用。The Copy method returns a String object that has the same value as the original string but represents a different object reference. 这不同于赋值操作,后者将现有字符串引用分配给其他对象变量。It differs from an assignment operation, which assigns an existing string reference to an additional object variable.

重要

从 .NET Core 3.0 开始,此方法已过时。Starting with .NET Core 3.0, this method is obsolete. 但是,我们不建议在任何 .NET 实现中使用。However, we do not recommend its use in any .NET implementation. 特别是,由于 .NET Core 3.0 中的字符串暂存发生了更改,因此,在某些情况下,Copy 方法不会创建新的字符串,而只会返回对现有暂存字符串的引用。In particular, because of changes in string interning in .NET Core 3.0, in some cases the Copy method will not create a new string but will simply return a reference to an existing interned string.

根据要调用 Copy 方法的原因,有许多替代方法:Depending on Why you want to call the Copy method, there are a number of alternatives:

  • 如果希望在修改字符串的操作中使用不同的字符串实例,请使用原始字符串实例。If you want a different string instance to use in an operation that modifies the string, use the original string instance. 因为字符串是不可变的,所以字符串操作会创建一个新的字符串实例,而原始字符串不受影响。Because strings are immutable, the string operation creates a new string instance, and the original string remains unaffected. 在这种情况下,不应将新字符串引用分配给原始字符串变量。In this case, you should not assign the new string reference to the original string variable. 下面的示例进行了这方面的演示。The following example provides an illustration.

    var original = "This is a sentence. This is a second sentence.";
    var sentence1 = original.Substring(0, original.IndexOf(".") + 1);
    Console.WriteLine(original);
    Console.WriteLine(sentence1);
    // The example displays the following output:
    //    This is a sentence. This is a second sentence.
    //    This is a sentence.            
    
    Dim original = "This is a sentence. This is a second sentence."
    Dim sentence1 = original.Substring(0, original.IndexOf(".") + 1)
    Console.WriteLine(original)
    Console.WriteLine(sentence1)
    ' The example displays the following output:
    '    This is a sentence. This is a second sentence.
    '    This is a sentence.            
    

    在这种情况下,调用 Copy 方法来创建一个新字符串,然后不必要地调用 Substring 方法会创建新的字符串实例。In this case, calling the Copy method to create a new string before calling the Substring method unnecessarily creates a new string instance.

  • 如果要创建具有与原始字符串相同的内容的可变缓冲区,请调用 String.ToCharArrayStringBuilder.StringBuilder(String) 构造函数。If you want to create a mutable buffer with the same contents as the original string, call the String.ToCharArray or StringBuilder.StringBuilder(String) constructor. 例如:For example:

    private static void UseMutableBuffer()
    {
        var original = "This is a sentence. This is a second sentence.";
        var chars = original.ToCharArray();
        var span = new Span<char>(chars);
        var slice = span.Slice(span.IndexOf('.'), 3);
        slice = MergeSentence(slice);
        Console.WriteLine($"Original string: {original}");
        Console.WriteLine($"Modified string: {span.ToString()}");
    
        static Span<char> MergeSentence(Span<char> span)
        {
            if (span.Length == 0) return Span<char>.Empty;
    
            span[0] = ';';
            span[2] = Char.ToLower(span[2]);
            return span;
        }
    }
    // The example displays the following output:
    //    Original string: This is a sentence. This is a second sentence.
    //    Modified string: This is a sentence; this is a second sentence.        
    
    Private Sub UseMutableBuffer()
        Dim original = "This is a sentence. This is a second sentence."
        Dim sb = new StringBuilder(original)
        Dim index = original.IndexOf(".")
        sb(index) = ";"
        sb(index + 2) = Char.ToLower(sb(index + 2))
        Console.WriteLine($"Original string: {original}")
        Console.WriteLine($"Modified string: {sb.ToString()}")
    End Sub
    ' The example displays the following output:
    '    Original string: This is a sentence. This is a second sentence.
    '    Modified string: This is a sentence; this is a second sentence.        
    
  • 如果要创建字符串的可变副本以便可以使用不安全代码修改字符串内容,请使用 Marshal.StringToHGlobalUni 方法。If you want to create a mutable copy of the string so that you can use unsafe code to modify the string contents, use Marshal.StringToHGlobalUni method. 下面的示例使用 Marshal.StringToHGlobalUni 方法获取指向非托管内存中复制的字符串的位置的指针,将字符串中每个字符的 Unicode 码位递增一,并将生成的字符串复制回托管字符串。The following example uses the Marshal.StringToHGlobalUni method to get a pointer to the location of an copied string in unmanaged memory, increments the Unicode code point of each character in the string by one, and copies the resulting string back to a managed string.

    private static void UseUnmanaged()
    {
        var original = "This is a single sentence.";
        var len = original.Length; 
        var ptr = Marshal.StringToHGlobalUni(original);
        string result;
        unsafe 
        {
            char *ch = (char *) ptr.ToPointer();
            while (len-- > 0)
            {
                char c = Convert.ToChar(Convert.ToUInt16(*ch) + 1);
                *ch++ = c;
            } 
            result = Marshal.PtrToStringUni(ptr);
            Marshal.FreeHGlobal(ptr);
        }
        Console.WriteLine($"Original string: {original}");
        Console.WriteLine($"String from interop: '{result}'");
    }
    // The example displays the following output:
    //    Original string: This is a single sentence.
    //    String from interop: 'Uijt!jt!b!tjohmf!tfoufodf/'      
    

适用于