String.Copy(String) String.Copy(String) String.Copy(String) String.Copy(String) Method

定義

警告

此 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 String String String

要複製的字串。The string to copy.

傳回

具有與 str 相同值的新字串。A new string with the same value as str.

例外狀況

備註

方法會傳回與原始字串具有相同值,但代表不同物件參考的物件。String CopyThe 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.        
    
  • 如果您想要建立字串的可變複本,讓您可以使用 unsafe 程式碼來修改字串內容,請使用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 程式碼點遞增一,然後將結果字串複製回 managed 字串。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/'      
    

適用於