String 建構函式

定義

初始化 String 類別的新執行個體。Initializes a new instance of the String class.

多載

String(Char*)

String 類別的新執行個體初始化為 Unicode 字元陣列的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

String(Char[])

String 類別新執行個體初始化為所指定字元陣列中指出的 Unicode 字元。Initializes a new instance of the String class to the Unicode characters indicated in the specified character array.

String(ReadOnlySpan<Char>)

String 類別新執行個體初始化為所指定唯讀範圍中指出的 Unicode 字元。Initializes a new instance of the String class to the Unicode characters indicated in the specified read-only span.

String(SByte*)

String 類別的新執行個體初始化為 8 位元帶正負號整數 (Signed Integer) 陣列的指標所指示的值。Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

String(Char, Int32)

String 類別的新執行個體初始化為由重複指定次數的指定 Unicode 字元所指示的值。Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

String(Char*, Int32, Int32)

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置以及長度等等的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

String(Char[], Int32, Int32)

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置和長度等等所指示的值。Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

String(SByte*, Int32, Int32)

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置和長度的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

String(SByte*, Int32, Int32, Encoding)

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置、長度和 Encoding 物件的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

備註

本節內容:In this section:

多載的函數語法Overloaded constructor syntax
參數Parameters
例外狀況Exceptions
我要呼叫哪個方法?Which method do I call?
建立字串Creating strings
處理重複的字串Handle repetitive strings

具現化字串的範例:Examples of instantiating strings:

使用字串指派Use string assignment
使用字元陣列Use a character array
使用字元陣列的一部分,並重複單一字元Use a portion of a character array and repeating a single character
使用字元陣列的指標Use a pointer to a character array
使用陣列的指標和範圍Use a pointer and a range of an array
使用帶正負號的位元組陣列的指標Use a pointer to a signed byte array
版本資訊Version information

多載的函數語法Overloaded constructor syntax

字串構造函式可分為兩類:沒有指標參數的類別,以及具有指標參數的分類。String constructors fall into two categories: those without pointer parameters, and those with pointer parameters. 使用指標的函式不符合 CLS 標準。The constructors that use pointers are not CLS-compliant. 此外,Visual Basic 不支援使用指標,而且C#需要使用指標在不安全的內容中執行的程式碼。In addition, Visual Basic does not support the use of pointers, and C# requires code that uses pointers to run in an unsafe context. 如需詳細資訊,請參閱 unsafeFor more information, see unsafe.

如需選擇多載的其他指引,請參閱我要呼叫哪一種方法?For additional guidance on choosing an overload, see Which method do I call?

String(Char[] value) 會將新的實例初始化為 Unicode 字元陣列所指示的值。String(Char[] value) Initializes the new instance to the value indicated by an array of Unicode characters. 此函式會複製 Unicode 字元(範例)。This constructor copies Unicode characters(example).

String(Char[] value, Int32 startIndex, Int32 length) 會將新的實例初始化為 Unicode 字元陣列、在該陣列內起始字元的位置,以及長度(範例)所指示的值。String(Char[] value, Int32 startIndex, Int32 length) Initializes the new instance to the value indicated by an array of Unicode characters, a starting character position within that array, and a length (example).

String(Char c, Int32 count) 將新的實例初始化為指定的 Unicode 字元所指示的值重複指定的次數(例如)。String(Char c, Int32 count) Initializes the new instance to the value indicated by a specified Unicode character repeated a specified number of times (example).

String(char* value) (不符合 CLS 標準) ,會將新的實例初始化為 Unicode 字元陣列的指標所指示的值(由 null 字元(U + 0000 或 ' \ 0 ')結束)。String(char* value) (Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of Unicode characters that is terminated by a null character (U+0000 or '\0'). 範例)。(example).

許可權: SecurityCriticalAttribute,必須完全信任立即呼叫者。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(char* value, Int32 startIndex, Int32 length) (不符合 CLS 標準) ,會將新的實例初始化為 Unicode 字元陣列、在該陣列內起始字元的位置,以及長度的指標所指示的值。String(char* value, Int32 startIndex, Int32 length) (Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of Unicode characters, a starting character position within that array, and a length. 此函式會 value 從索引 startIndex 開始複製 Unicode 字元,並在索引 startIndex + length-1 (範例)結束。The constructor copies the Unicode characters from value starting at index startIndex and ending at index startIndex + length - 1 (example).

許可權: SecurityCriticalAttribute,必須完全信任立即呼叫者。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(SByte* value) (不符合 CLS 標準)會將新的實例初始化為8位帶正負號整數陣列的指標所指示的值。String(SByte* value) (Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. 陣列會假設為使用目前的系統字碼頁(也就是 Encoding.Default所指定的編碼)來編碼的字串。The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by Encoding.Default). 此函式會處理從指標指定的位置開始 value 的字元,直到達到 null 字元(例如)為止。The constructor processes characters from value starting from the location specified by the pointer until a null character (0x00) is reached (example).

許可權: SecurityCriticalAttribute,必須完全信任立即呼叫者。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(SByte* value, Int32 startIndex, Int32 length) (不符合 CLS 標準)會將新的實例初始化為8位帶正負號整數的陣列、在該陣列內開始位置和長度的指標所指示的值。String(SByte* value, Int32 startIndex, Int32 length) (Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, and a length. 陣列會假設為使用目前的系統字碼頁(也就是 Encoding.Default所指定的編碼)來編碼的字串。The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by Encoding.Default). 此函式會從 startIndex 開始處理值的字元,並在 startIndex + length-1 (範例)結束。The constructor processes characters from value starting at startIndex and ending at startIndex + length - 1 (example).

許可權: SecurityCriticalAttribute,必須完全信任立即呼叫者。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(SByte* value, Int32 startIndex, Int32 length, Encoding enc) (不符合 CLS 標準)會將新的實例初始化為8位帶正負號整數的陣列、在該陣列內開始位置、長度和 Encoding 物件的指標所指示的值。String(SByte* value, Int32 startIndex, Int32 length, Encoding enc) (Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

許可權: SecurityCriticalAttribute,必須完全信任立即呼叫者。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

參數Parameters

以下是不包含指標參數 String 的函式所使用之參數的完整清單。Here is a complete list of parameters used by String constructors that don't include a pointer parameter. 如需每個多載所使用的參數,請參閱上述的多載語法。For the parameters used by each overload, see the overload syntax above.

參數Parameter TypeType 說明Description
value Char[]Char[] Unicode 字元陣列。An array of Unicode characters.
c Char Unicode 字元。A Unicode character.
startIndex Int32 新字串中第一個字元 value 中的開始位置。The starting position in value of the first character in the new string.

預設值:0Default value: 0
length Int32 value 中要包含在新字串中的字元數。The number of characters in value to include in the new string.

預設值: Array.LengthDefault value: Array.Length
count Int32 字元 c 在新字串中重複出現的次數。The number of times the character c is repeated in the new string. 如果 count 為零,則會 String.Empty新物件的值。If count is zero, the value of the new object is String.Empty.

以下是包含指標參數 String 的函式所使用之參數的完整清單。Here is a complete list of parameters used by String constructors that include a pointer parameter. 如需每個多載所使用的參數,請參閱上述的多載語法。For the parameters used by each overload, see the overload syntax above.

參數Parameter TypeType 說明Description
value Char*

-或--or-

SByte*
以 null 結束的 Unicode 字元陣列或8位帶正負號整數陣列的指標。A pointer to a null-terminated array of Unicode characters or an array of 8-bit signed integers. 如果 valuenull 或空陣列,則會 String.Empty新字串的值。If value is null or an empty array, the value of the new string is String.Empty.
startIndex Int32 陣列元素的索引,定義新字串中的第一個字元。The index of the array element that defines the first character in the new string.

預設值:0Default value: 0
length Int32 要用來建立新字串的陣列元素數目。The number of array elements to use to create the new string. 如果 length 為零,則此函式會建立字串,其值為 String.EmptyIf length is zero, the constructor creates a string whose value is String.Empty.

預設值: Array.LengthDefault value: Array.Length
enc Encoding 物件,指定如何編碼 value 陣列。An object that specifies how the value array is encoded.

預設值: Encoding.Default或系統目前的 ANSI 字碼頁Default value: Encoding.Default, or the system's current ANSI code page

例外狀況Exceptions

以下是不包含指標參數的函式所擲回的例外狀況清單。Here's a list of exceptions thrown by constructors that don't include pointer parameters.

例外狀況Exception 條件Condition 擲回者Thrown by
ArgumentNullException valuenullvalue is null. String(Char[], Int32, Int32)
ArgumentOutOfRangeException startIndexlengthcount 小於零。startIndex,length, or count is less than zero.

-或--or-

startIndexlength 的總和大於 value 中的項目數。The sum of startIndex and length is greater than the number of elements in value.

-或--or-

count 小於零。count is less than zero.
String(Char, Int32)

String(Char[], Int32, Int32)

以下是包含指標參數的函式所擲回的例外狀況清單。Here's a list of exceptions thrown by constructors that include pointer parameters.

例外狀況Exception 條件Condition 擲回者Thrown by
ArgumentException value 指定包含無效 Unicode 字元的陣列。value specifies an array that contains an invalid Unicode character.

-或--or-

valuevalue + startIndex 指定的位址小於64K。value or value + startIndex specifies an address that is less than 64K.

-或--or-

無法從 value 位元組陣列初始化新的 String 實例,因為 value 不會使用預設字碼頁編碼。A new String instance could not be initialized from the value byte array because value does not use the default code page encoding.
具有指標的所有函式。All constructors with pointers.
ArgumentNullException value 為 null。value is null. String(SByte*)

String(SByte*, Int32, Int32)

String(SByte*, Int32, Int32, Encoding)
ArgumentOutOfRangeException 目前的處理序沒有讀取所有定址字元的權限。The current process does not have read access to all the addressed characters.

-或--or-

startIndexlength 小於零、value + startIndex 導致指標溢位,或目前的處理序沒有所有定址字元的讀取權限。startIndex or length is less than zero, value + startIndex cause a pointer overflow, or the current process does not have read access to all the addressed characters.

-或--or-

新字串的長度太大,無法配置。The length of the new string is too large to allocate.
具有指標的所有函式。All constructors with pointers.
AccessViolationException valuevalue + startIndex + length-1)指定了不正確位址。value, or value + startIndex + length - 1, specifies an invalid address. String(SByte*)

String(SByte*, Int32, Int32)

String(SByte*, Int32, Int32, Encoding)

我要呼叫哪個方法?Which method do I call?

To 呼叫或使用Call or use
建立字串。Create a string. 從字串常值或現有字串進行指派(範例Assignment from a string literal or an existing string (example)
從整個字元陣列建立字串。Create a string from an entire character array. String(Char[])範例String(Char[]) (example)
從字元陣列的一部分建立字串。Create a string from a portion of a character array. String(Char[], Int32, Int32)範例String(Char[], Int32, Int32) (example)
建立重複相同字元多次的字串。Create a string that repeats the same character multiple times. String(Char, Int32)範例String(Char, Int32) (example)
從 Unicode 或寬字元陣列的指標建立字串。Create a string from a pointer to a Unicode or wide character array. String(Char*)
使用它的指標,從 Unicode 或寬字元陣列的一部分建立字串。Create a string from a portion of a Unicode or wide character array by using its pointer. String(Char*, Int32, Int32)
從C++ char 陣列建立字串。Create a string from a C++ char array. String(SByte*)String(SByte*, Int32, Int32)String(SByte*), String(SByte*, Int32, Int32)

-或--or-

String(SByte*, Int32, Int32, Encoding)
從 ASCII 字元建立字串。Create a string from ASCII characters. ASCIIEncoding.GetString

建立字串Create strings

以程式設計方式建立字串最常用的技巧是簡單的指派,如下列範例所示。The most commonly used technique for creating strings programmatically is simple assignment, as illustrated in this example. String 類別也包含四種類型的函數多載,可讓您從下列值建立字串:The String class also includes four types of constructor overloads that let you create strings from the following values:

  • 從字元陣列(UTF-16 編碼字元的陣列)。From a character array (an array of UTF-16-encoded characters). 您可以從整個陣列中的字元或其中一部分,建立新的 String 物件。You can create a new String object from the characters in the entire array or a portion of it. String(Char[]) 的構造函式會將陣列中的所有字元複製到新的字串。The String(Char[]) constructor copies all the characters in the array to the new string. String(Char[], Int32, Int32) 的函式會將索引 startIndex 中的字元複製到索引 startIndex + length-1 到新字串。The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length - 1 to the new string. 如果 length 為零,則會 String.Empty新字串的值。If length is zero, the value of the new string is String.Empty.

    如果您的程式碼重複具現化具有相同值的字串,您可以使用建立字串的替代方法來改善應用程式效能。If your code repeatedly instantiates strings that have the same value, you can improve application performance by using an alternate means of creating strings. 如需詳細資訊,請參閱處理重複的字串For more information, see Handling repetitive strings.

  • 使用 String(Char, Int32) 的方法,從重複零次、一次或多次的單一字元。From a single character that is duplicated zero, one, or more times, by using the String(Char, Int32) constructor. 如果 count 為零,則會 String.Empty新字串的值。If count is zero, the value of the new string is String.Empty.

  • 從以 null 結束的字元陣列的指標,使用 String(Char*)String(Char*, Int32, Int32) 的「函數」。From a pointer to a null-terminated character array, by using the String(Char*) or String(Char*, Int32, Int32) constructor. 整個陣列或指定的範圍都可以用來初始化字串。Either the entire array or a specified range can be used to initialize the string. 此函式會從指定的指標或指定的指標加號開始複製 Unicode 字元序列,再加上 startIndex 並繼續到陣列的結尾或 length 字元。The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plus startIndex and continuing to the end of the array or for length characters. 如果 value 為 null 指標,或 length 為零,則此函式會建立一個字串,其值為 String.EmptyIf value is a null pointer or length is zero, the constructor creates a string whose value is String.Empty. 如果複製作業繼續到陣列結尾,且陣列不是以 null 終止,則此函式行為會與系統相依。If the copy operation proceeds to the end of the array and the array is not null-terminated, the constructor behavior is system-dependent. 這類條件可能會造成存取違規。Such a condition might cause an access violation.

    如果陣列包含任何內嵌的 null 字元(U + 0000 或 ' \ 0 '),而且呼叫了 String(Char*, Int32, Int32) 多載,則字串實例會包含 length 字元,包括任何內嵌的 null。If the array contains any embedded null characters (U+0000 or '\0') and the String(Char*, Int32, Int32) overload is called, the string instance contains length characters including any embedded nulls. 下列範例顯示將包含兩個 null 字元的10個元素陣列指標傳遞給 String(Char*, Int32, Int32) 方法時,會發生什麼事。The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the String(Char*, Int32, Int32) method. 因為位址是陣列的開頭,而陣列中的所有元素都要加入字串中,所以此函式會將包含10個字元的字串具現化,包括兩個內嵌的 null。Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. 另一方面,如果將相同的陣列傳遞給 String(Char*) 的函式,則結果會是不包含第一個 null 字元的四個字元字串。On the other hand, if the same array is passed to the String(Char*) constructor, the result is a four-character string that does not include the first null character.

    using namespace System;
    
    void main()
    {
       wchar_t chars[] = { L'a', L'b', L'c', L'd', L'\0', L'A', L'B', 
                           L'C', L'D', L'\0' };
       Char* chPtr = chars;
       String^ s = gcnew String(chPtr, 0, 
                                sizeof(chars) / sizeof (wchar_t));            
       for each (Char ch in s)
          Console::Write("{0:X4} ", Convert::ToUInt16(ch));
       Console::WriteLine();
       
       s = gcnew String(chPtr);         
       
       for each (Char ch in s)
          Console::Write("{0:X4} ", Convert::ToUInt16(ch));
       Console::WriteLine();    
    }
    // The example displays the following output:
    //       0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
    //       0061 0062 0063 0064
    
    using System;
    
    public class Example
    {
       public unsafe static void Main()
       {
          char[] chars = { 'a', 'b', 'c', 'd', '\0', 'A', 'B', 'C', 'D', '\0' };
          string s = null;
          
          fixed(char* chPtr = chars) {
             s = new string(chPtr, 0, chars.Length);            
          } 
    
          foreach (var ch in s)
             Console.Write("{0:X4} ", Convert.ToUInt16(ch));
          Console.WriteLine();
          
          fixed(char* chPtr = chars) {
             s = new string(chPtr);         
          }
          
          foreach (var ch in s)
             Console.Write("{0:X4} ", Convert.ToUInt16(ch));
          Console.WriteLine();    
       }
    }
    // The example displays the following output:
    //       0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
    //       0061 0062 0063 0064
    

    陣列必須包含 Unicode 字元。The array must contain Unicode characters. 在C++中,這表示字元陣列必須定義為 managed Char[] 類型或非受控wchar_t[] 類型。In C++, this means that the character array must be defined either as the managed Char[] type or the unmanagedwchar_t[] type.

    如果呼叫 String(Char*) 多載,且陣列不是以 null 終止,或呼叫 String(Char*, Int32, Int32) 多載,且 startIndex + length-1 包含超出為字元序列所配置之記憶體的範圍,則此函式的行為會與系統相依,而且可能會發生存取違規。If the String(Char*) overload is called and the array is not null-terminated, or if the String(Char*, Int32, Int32) overload is called and startIndex + length-1 includes a range that it outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. 此外,在 Intel Itanium 處理器上,呼叫 String(Char*, Int32, Int32) 的函數可能會擲回 DataMisalignedException 例外狀況。In addition, on the Intel Itanium processor, calls to the String(Char*, Int32, Int32) constructor may throw a DataMisalignedException exception. 如果發生這種情況,請改為呼叫 String(Char[], Int32, Int32)If this occurs, call the String(Char[], Int32, Int32) instead.

  • 從帶正負號的位元組陣列的指標。From a pointer to a signed byte array. 整個陣列或指定的範圍都可以用來初始化字串。Either the entire array or a specified range can be used to initialize the string. 您可以使用預設字碼頁編碼來解讀位元組序列,或者可以在此函式呼叫中指定編碼方式。The sequence of bytes can be interpreted by using the default code page encoding, or an encoding can be specified in the constructor call. 如果此函式嘗試從整個不是以 null 結束的陣列具現化字串,或從 value的陣列範圍 + startIndexvalue + startIndex + -1 不在配置給陣列的記憶體中,則此函式的行為會與系統相依,而且可能會發生存取違規。lengthIf the constructor tries to instantiate a string from an entire array that is not null-terminated, or if the range of the array from value + startIndex to value + startIndex + length -1 is outside of the memory allocated for the array, the behavior of this constructor is system-dependent, and an access violation may occur.

    包含帶正負號的位元組陣列做為參數的三個函式,主要是C++用來將 char 陣列轉換成字串,如下列範例所示:The three constructors that include a signed byte array as a parameter are designed primarily to convert a C++ char array to a string, as shown in this example:

    using namespace System;
    
    void main()
    {
          char chars[] = { 'a', 'b', 'c', 'd', '\x00' };
          
          char* charPtr = chars;
          String^ value = gcnew String(charPtr);
    
          Console::WriteLine(value);
    }
    // The example displays the following output:
    //      abcd
    

    如果陣列包含任何 null 字元(' \ 0 ')或值為0的位元組,而且呼叫 String(SByte*, Int32, Int32) 多載,則字串實例會包含 length 字元,包括任何內嵌的 null。If the array contains any null characters ('\0') or bytes whose value is 0 and the String(SByte*, Int32, Int32) overload is called, the string instance contains length characters including any embedded nulls. 下列範例顯示將包含兩個 null 字元的10個元素陣列指標傳遞給 String(SByte*, Int32, Int32) 方法時,會發生什麼事。The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the String(SByte*, Int32, Int32) method. 因為位址是陣列的開頭,而陣列中的所有元素都要加入字串中,所以此函式會將包含10個字元的字串具現化,包括兩個內嵌的 null。Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. 另一方面,如果將相同的陣列傳遞給 String(SByte*) 的函式,則結果會是不包含第一個 null 字元的四個字元字串。On the other hand, if the same array is passed to the String(SByte*) constructor, the result is a four-character string that does not include the first null character.

    using namespace System;
    
    void main()
    {
       char bytes[] = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42,0x43, 
                        0x44, 0x00 };
       
       char* bytePtr = bytes;
       String^ s = gcnew String(bytePtr, 0, sizeof(bytes) / sizeof (char));
       
       for each (Char ch in s)
          Console::Write("{0:X4} ", Convert::ToUInt16(ch));
       
       Console::WriteLine();
       
       s = gcnew String(bytePtr);
    
       for each (Char ch in s)
          Console::Write("{0:X4} ", Convert::ToUInt16(ch));
       Console::WriteLine();       
    }
    // The example displays the following output:
    //      0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
    //      0061 0062 0063 0064
    
    using System;
    
    public class Example
    {
       public unsafe static void Main()
       {
          sbyte[] bytes = { 0x61, 0x62, 0x063, 0x064, 0x00, 0x41, 0x42,0x43, 0x44, 0x00 };
          
          string s = null;
          fixed (sbyte* bytePtr = bytes) {
             s = new string(bytePtr, 0, bytes.Length);
          }
          
          foreach (var ch in s)
             Console.Write("{0:X4} ", Convert.ToUInt16(ch));
          
          Console.WriteLine();    
    
          fixed(sbyte* bytePtr = bytes) {
             s = new string(bytePtr);         
          }
          
          foreach (var ch in s)
             Console.Write("{0:X4} ", Convert.ToUInt16(ch));
          Console.WriteLine();    
       }
    }
    // The example displays the following output:
    //       0061 0062 0063 0064 0000 0041 0042 0043 0044 0000
    //       0061 0062 0063 0064
    

    因為 String(SByte*)String(SByte*, Int32, Int32) 的中繼資料會使用預設的 ANSI 字碼頁來解讀 value,所以以相同的位元組陣列呼叫這些函式,可能會在不同的系統上建立具有不同值的字串。Because the String(SByte*) and String(SByte*, Int32, Int32) constructors interpret value by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems.

處理重複的字串Handle repetitive strings

剖析或解碼文字資料流程的應用程式通常會使用 String(Char[], Int32, Int32) 的函數或 StringBuilder.Append(Char[], Int32, Int32) 方法,將字元序列轉換成字串。Apps that parse or decode streams of text often use the String(Char[], Int32, Int32) constructor or the StringBuilder.Append(Char[], Int32, Int32) method to convert sequences of characters into a string. 重複建立具有相同值的新字串,而不是建立和重複使用一個字串會浪費記憶體。Repeatedly creating new strings with the same value instead of creating and reusing one string wastes memory. 如果您可能會藉由呼叫 String(Char[], Int32, Int32) 的函式來重複建立相同的字串值,即使您事先不知道那些完全相同的字串值,也可以改用查閱資料表。If you are likely to create the same string value repeatedly by calling the String(Char[], Int32, Int32) constructor, even if you don't know in advance what those identical string values may be, you can use a lookup table instead.

例如,假設您從包含 XML 標記和屬性的檔案讀取和剖析字元資料流。For example, suppose you read and parse a stream of characters from a file that contains XML tags and attributes. 當您剖析資料流程時,會重複出現某些標記(也就是具有符號意義的字元序列)。When you parse the stream, you repeatedly encounter certain tokens (that is, sequences of characters that have a symbolic meaning). 對應至字串 "0"、"1"、"true" 和 "false" 的權杖,可能會經常出現在 XML 資料流程中。Tokens equivalent to the strings "0", "1", "true", and "false" are likely to occur frequently in an XML stream.

您可以建立 System.Xml.NameTable 物件來保存經常發生的字串,而不是將每個 token 轉換成新的字串。Instead of converting each token into a new string, you can create a System.Xml.NameTable object to hold commonly occurring strings. NameTable 物件會改善效能,因為它會在不配置暫存記憶體的情況下,抓取儲存的字串。The NameTable object improves performance, because it retrieves stored strings without allocating temporary memory. 當您遇到權杖時,請使用 NameTable.Get(Char[], Int32, Int32) 方法,從資料表中取出 token。When you encounter a token, use the NameTable.Get(Char[], Int32, Int32) method to retrieve the token from the table. 如果權杖存在,則方法會傳回對應的字串。If the token exists, the method returns the corresponding string. 如果權杖不存在,請使用 NameTable.Add(Char[], Int32, Int32) 方法,將 token 插入資料表中,並取得對應的字串。If the token does not exist, use the NameTable.Add(Char[], Int32, Int32) method to insert the token into the table and to get the corresponding string.

範例1:使用字串指派Example 1: Use string assignment

下列範例會將字串常值指派給它,藉以建立新的字串。The following example creates a new string by assigning it a string literal. 它會將第一個字串的值指派給它,藉以建立第二個字串。It creates a second string by assigning the value of the first string to it. 這些是具現化新 String 物件的兩個最常見方式。These are the two most common ways to instantiate a new String object.

using namespace System;

void main()
{
   String^ value1 = L"This is a string.";
   String^ value2 = value1;
   Console::WriteLine(value1);
   Console::WriteLine(value2);
}
// The example displays the following output:
//    This is a string.
//    This is a string.
using System;

public class Example
{
   public static void Main()
   {
      String value1 = "This is a string.";
      String value2 = value1;
      Console.WriteLine(value1);
      Console.WriteLine(value2);
   }
}
// The example displays the following output:
//    This is a string.
//    This is a string.
Module Example
   Public Sub Main()
      Dim value1 As String = "This is a string."
      Dim value2 As String = value1
      Console.WriteLine(value1)
      Console.WriteLine(value2)
   End Sub
End Module
' The example displays the following output:
'    This is a string.
'    This is a string.

範例2:使用字元陣列Example 2: Use a character array

下列範例示範如何從字元陣列建立新的 String 物件。The following example demonstrates how to create a new String object from a character array.

// Unicode Mathematical operators
wchar_t charArray1[4] = {L'\x2200',L'\x2202',L'\x200F',L'\x2205'};
wchar_t * lptstr1 =  &charArray1[ 0 ];
String^ wszMathSymbols = gcnew String( lptstr1 );

// Unicode Letterlike Symbols
wchar_t charArray2[4] = {L'\x2111',L'\x2118',L'\x2122',L'\x2126'};
wchar_t * lptstr2 =  &charArray2[ 0 ];
String^ wszLetterLike = gcnew String( lptstr2 );

// Compare Strings - the result is false
Console::WriteLine( String::Concat( L"The Strings are equal? ", (0 == String::Compare( wszLetterLike, wszMathSymbols ) ? (String^)"TRUE" : "FALSE") ) );
// Unicode Mathematical operators
char [] charArr1 = {'\u2200','\u2202','\u200F','\u2205'};
String szMathSymbols = new String(charArr1);

// Unicode Letterlike Symbols
char [] charArr2 = {'\u2111','\u2118','\u2122','\u2126'};
String szLetterLike = new String (charArr2);

// Compare Strings - the result is false
Console.WriteLine("The Strings are equal? " +
    (String.Compare(szMathSymbols, szLetterLike)==0?"true":"false") );
' Unicode Mathematical operators
Dim charArr1() As Char = {ChrW(&H2200), ChrW(&H2202), _
                          ChrW(&H200F), ChrW(&H2205)}
Dim szMathSymbols As New String(charArr1)

' Unicode Letterlike Symbols
Dim charArr2() As Char = {ChrW(&H2111), ChrW(&H2118), _
                          ChrW(&H2122), ChrW(&H2126)}
Dim szLetterLike As New String(charArr2)

' Compare Strings - the result is false
Console.WriteLine("The strings are equal? " & _
        CStr(szMathSymbols.Equals(szLetterLike))) 

範例3:使用字元陣列的一部分,並重複單一字元Example 3: Use a portion of a character array and repeating a single character

下列範例示範如何從字元陣列的一部分建立新的 String 物件,以及如何建立新的 String 物件,其中包含多個出現的單一字元。The following example demonstrates how to create a new String object from a portion of a character array, and how to create a new String object that contains multiple occurrences of a single character.

// Create a Unicode String with 5 Greek Alpha characters
String^ szGreekAlpha = gcnew String( L'\x0391',5 );

// Create a Unicode String with a Greek Omega character
wchar_t charArray5[3] = {L'\x03A9',L'\x03A9',L'\x03A9'};
String^ szGreekOmega = gcnew String( charArray5,2,1 );
String^ szGreekLetters = String::Concat( szGreekOmega, szGreekAlpha, szGreekOmega->Clone() );

// Examine the result
Console::WriteLine( szGreekLetters );

// The first index of Alpha
int ialpha = szGreekLetters->IndexOf( L'\x0391' );

// The last index of Omega
int iomega = szGreekLetters->LastIndexOf( L'\x03A9' );
Console::WriteLine( String::Concat(  "The Greek letter Alpha first appears at index ", Convert::ToString( ialpha ) ) );
Console::WriteLine( String::Concat(  " and Omega last appears at index ", Convert::ToString( iomega ),  " in this String." ) );
// Create a Unicode String with 5 Greek Alpha characters
String szGreekAlpha = new String('\u0391',5);
// Create a Unicode String with a Greek Omega character
String szGreekOmega = new String(new char [] {'\u03A9','\u03A9','\u03A9'},2,1);

String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone());

// Examine the result
Console.WriteLine(szGreekLetters);

// The first index of Alpha
int ialpha = szGreekLetters.IndexOf('\u0391');
// The last index of Omega
int iomega = szGreekLetters.LastIndexOf('\u03A9');

Console.WriteLine("The Greek letter Alpha first appears at index " + ialpha +
    " and Omega last appears at index " + iomega + " in this String.");
' Create a Unicode String with 5 Greek Alpha characters
Dim szGreekAlpha As New String(ChrW(&H0391), 5)
' Create a Unicode String with a Greek Omega character
Dim szGreekOmega As New String(New Char() {ChrW(&H03A9), ChrW(&H03A9), _
                                           ChrW(&H03A9)}, 2, 1)

Dim szGreekLetters As String = String.Concat(szGreekOmega, szGreekAlpha, _
                                             szGreekOmega.Clone())

' Examine the result
Console.WriteLine(szGreekLetters)

' The first index of Alpha
Dim iAlpha As Integer = szGreekLetters.IndexOf(ChrW(&H0391))
' The last index of Omega
Dim iomega As Integer = szGreekLetters.LastIndexOf(ChrW(&H03A9))

Console.WriteLine("The Greek letter Alpha first appears at index {0}.", _ 
                  ialpha)
Console.WriteLIne("The Greek letter Omega last appears at index {0}.", _
                  iomega)

範例4:使用字元陣列的指標Example 4: Use a pointer to a character array

下列範例示範如何從字元陣列的指標建立新的 String 物件。The following example demonstrates how to create a new String object from a pointer to an array of characters. 您C#必須使用 /unsafe 編譯器參數來編譯此範例。The C# example must be compiled by using the /unsafe compiler switch.

using namespace System;

void main()
{
   wchar_t characters[] = {L'H',L'e',L'l',L'l',L'o',L' ', 
                           L'W',L'o',L'r',L'l',L'd',L'!',L'\x0000'};

   Char* charPtr = characters;
   String^ value = gcnew String(charPtr);
   Console::WriteLine(value);
}
// The example displays the following output:
//        Hello world!
using System;

public class Example
{
   public static unsafe void Main()
   {
      char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', 
                            'w', 'o', 'r', 'l', 'd', '!', '\u0000' };
      string value;
      
      fixed (char* charPtr = characters) {
         value = new String(charPtr);
      }                            
      Console.WriteLine(value);
   }
}
// The example displays the following output:
//        Hello world!

範例5:從指標和陣列範圍將字串具現化Example 5: Instantiate a string from a pointer and a range of an array

下列範例會檢查字元陣列的元素是否有句號或驚嘆號。The following example examines the elements of a character array for either a period or an exclamation point. 如果找到一個,就會從陣列中的字元(在標點符號前面)中,將字串具現化。If one is found, it instantiates a string from the characters in the array that precede the punctuation symbol. 如果不是,則會使用陣列的完整內容來具現化字串。If not, it instantiates a string with the entire contents of the array. 您C#必須使用 /unsafe 編譯器參數來編譯此範例。The C# example must be compiled using the /unsafe compiler switch.

using namespace System;


void main()
{
   wchar_t characters[] = {L'H',L'e',L'l',L'l',L'o',L' ', 
                           L'W',L'o',L'r',L'l',L'd',L'!',L'\x0000'};

   Char* charPtr = characters;
   int length = 0;
   Char* iterator = charPtr;

   while (*iterator != '\x0000')
   {
      if (*iterator == L'!' || *iterator == L'.')
         break;
      *iterator++;
      length++;
   }
   String^ value = gcnew String(charPtr, 0, length);
   Console::WriteLine(value);
}
// The example displays the following output:
//      Hello World
using System;

public class Example
{
   public static unsafe void Main()
   {
      char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', 
                            'w', 'o', 'r', 'l', 'd', '!', '\u0000' };
      String value;
      
      fixed (char* charPtr = characters) {
         int length = 0;
         Char* iterator = charPtr;
   
         while (*iterator != '\x0000')
         {
            if (*iterator == '!' || *iterator == '.')
               break;
            iterator++;
            length++;
         }
         value = new String(charPtr, 0, length);
      }
      Console.WriteLine(value);
   }
}
// The example displays the following output:
//      Hello World

範例6:從帶正負號的位元組陣列的指標具現化字串Example 6: Instantiate a string from a pointer to a signed byte array

下列範例示範如何使用 String(SByte*) 的函式來建立 String 類別的實例。The following example demonstrates how you can create an instance of the String class with the String(SByte*) constructor.

// Null terminated ASCII characters in a simple char array
char charArray3[4] = {0x41,0x42,0x43,0x00};
char * pstr3 =  &charArray3[ 0 ];
String^ szAsciiUpper = gcnew String( pstr3 );
char charArray4[4] = {0x61,0x62,0x63,0x00};
char * pstr4 =  &charArray4[ 0 ];
String^ szAsciiLower = gcnew String( pstr4,0,sizeof(charArray4) );

// Prints "ABC abc"
Console::WriteLine( String::Concat( szAsciiUpper,  " ", szAsciiLower ) );

// Compare Strings - the result is true
Console::WriteLine( String::Concat(  "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper->ToUpper(), szAsciiLower->ToUpper() ) ? (String^)"TRUE" :  "FALSE") ) );

// This is the effective equivalent of another Compare method, which ignores case
Console::WriteLine( String::Concat(  "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper, szAsciiLower, true ) ? (String^)"TRUE" :  "FALSE") ) );
unsafe
{
    // Null terminated ASCII characters in an sbyte array
    String szAsciiUpper = null;
    sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 };
    // Instruct the Garbage Collector not to move the memory
    fixed(sbyte* pAsciiUpper = sbArr1)
    {
        szAsciiUpper = new String(pAsciiUpper);
    }
    String szAsciiLower = null;
    sbyte[] sbArr2 = { 0x61, 0x62, 0x63, 0x00 };
    // Instruct the Garbage Collector not to move the memory
    fixed(sbyte* pAsciiLower = sbArr2)
    {
        szAsciiLower = new String(pAsciiLower, 0, sbArr2.Length);
    }
    // Prints "ABC abc"
    Console.WriteLine(szAsciiUpper + " " + szAsciiLower);

    // Compare Strings - the result is true
    Console.WriteLine("The Strings are equal when capitalized ? " +
        (String.Compare(szAsciiUpper.ToUpper(), szAsciiLower.ToUpper())==0?"true":"false") );

    // This is the effective equivalent of another Compare method, which ignores case
    Console.WriteLine("The Strings are equal when capitalized ? " +
        (String.Compare(szAsciiUpper, szAsciiLower, true)==0?"true":"false") );
}

版本資訊Version information

.NET Framework 支援所有多載:4.5、4、3.5、3.0、2.0、1.1、1。0.NET Framework All overloads are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework 的用戶端設定檔:4、3.5 SP1 中支援所有多載.NET Framework Client Profile All overloads are supported in: 4, 3.5 SP1

可移植類別庫支援不含 SByte* 參數的所有多載Portable Class Library All overloads without an SByte* parameter are supported

適用于 Windows Store 應用程式的 .NET: Windows 8 支援不含 SByte* 參數的所有多載.NET for Windows Store apps All overloads without an SByte* parameter are supported in: Windows 8

String(Char*)

重要

此 API 不符合 CLS 規範。

String 類別的新執行個體初始化為 Unicode 字元陣列的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

public:
 String(char* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (char* value);
new string : nativeptr<char> -> string

參數

value
Char*

Unicode 字元之 Null 終端陣列的指標A pointer to a null-terminated array of Unicode characters.

屬性

例外狀況

目前的處理序沒有讀取所有定址字元的權限。The current process does not have read access to all the addressed characters.

value 指定包含無效 Unicode 字元的陣列,或 value 指定小於 64000 的位址。value specifies an array that contains an invalid Unicode character, or value specifies an address less than 64000.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(Char[])

String 類別新執行個體初始化為所指定字元陣列中指出的 Unicode 字元。Initializes a new instance of the String class to the Unicode characters indicated in the specified character array.

public:
 String(cli::array <char> ^ value);
public String (char[] value);
new string : char[] -> string
Public Sub New (value As Char())

參數

value
Char[]

Unicode 字元陣列。An array of Unicode characters.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(ReadOnlySpan<Char>)

String 類別新執行個體初始化為所指定唯讀範圍中指出的 Unicode 字元。Initializes a new instance of the String class to the Unicode characters indicated in the specified read-only span.

public:
 String(ReadOnlySpan<char> value);
public String (ReadOnlySpan<char> value);
new string : ReadOnlySpan<char> -> string
Public Sub New (value As ReadOnlySpan(Of Char))

參數

value
ReadOnlySpan<Char>

Unicode 字元的唯讀範圍。A read-only span of Unicode characters.

String(SByte*)

重要

此 API 不符合 CLS 規範。

String 類別的新執行個體初始化為 8 位元帶正負號整數 (Signed Integer) 陣列的指標所指示的值。Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

public:
 String(System::SByte* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value);
new string : nativeptr<sbyte> -> string

參數

value
SByte*

以 null 結束之 8 位元帶正負號整數的陣列指標。A pointer to a null-terminated array of 8-bit signed integers. 整數會使用目前的系統字碼頁編碼來解譯 (也就是由 Default 所指定的編碼)。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).

屬性

例外狀況

valuenullvalue is null.

無法使用 String 初始化 value 的新執行個體,假設 value 是 ANSI 編碼。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.

要初始化的新字串長度,由 value 之 null 結束字元所決定,該長度太長而無法配置。The length of the new string to initialize, which is determined by the null termination character of value, is too large to allocate.

value 指定了無效的位址。value specifies an invalid address.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(Char, Int32)

String 類別的新執行個體初始化為由重複指定次數的指定 Unicode 字元所指示的值。Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

public:
 String(char c, int count);
public String (char c, int count);
new string : char * int -> string
Public Sub New (c As Char, count As Integer)

參數

c
Char

Unicode 字元。A Unicode character.

count
Int32

c 發生的次數。The number of times c occurs.

例外狀況

count 小於零。count is less than zero.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(Char*, Int32, Int32)

重要

此 API 不符合 CLS 規範。

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置以及長度等等的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

public:
 String(char* value, int startIndex, int length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (char* value, int startIndex, int length);
new string : nativeptr<char> * int * int -> string

參數

value
Char*

Unicode 字元陣列的指標。A pointer to an array of Unicode characters.

startIndex
Int32

開始位置在 value 內。The starting position within value.

length
Int32

value 內要使用的字元數。The number of characters within value to use.

屬性

例外狀況

startIndexlength 小於零、value + startIndex 導致指標溢位,或目前的處理序沒有所有定址字元的讀取權限。startIndex or length is less than zero, value + startIndex cause a pointer overflow, or the current process does not have read access to all the addressed characters.

value 指定包含無效 Unicode 字元的陣列,或 value + startIndex 指定小於 64000 的位址。value specifies an array that contains an invalid Unicode character, or value + startIndex specifies an address less than 64000.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(Char[], Int32, Int32)

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置和長度等等所指示的值。Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

public:
 String(cli::array <char> ^ value, int startIndex, int length);
public String (char[] value, int startIndex, int length);
new string : char[] * int * int -> string
Public Sub New (value As Char(), startIndex As Integer, length As Integer)

參數

value
Char[]

Unicode 字元陣列。An array of Unicode characters.

startIndex
Int32

開始位置在 value 內。The starting position within value.

length
Int32

value 內要使用的字元數。The number of characters within value to use.

例外狀況

valuenullvalue is null.

startIndexlength 小於零。startIndex or length is less than zero.

-或--or-

startIndexlength 的總和大於 value 中的項目數。The sum of startIndex and length is greater than the number of elements in value.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(SByte*, Int32, Int32)

重要

此 API 不符合 CLS 規範。

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置和長度的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

public:
 String(System::SByte* value, int startIndex, int length);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value, int startIndex, int length);
new string : nativeptr<sbyte> * int * int -> string

參數

value
SByte*

8 位元帶正負號整數陣列的指標。A pointer to an array of 8-bit signed integers. 整數會使用目前的系統字碼頁編碼來解譯 (也就是由 Default 所指定的編碼)。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).

startIndex
Int32

開始位置在 value 內。The starting position within value.

length
Int32

value 內要使用的字元數。The number of characters within value to use.

屬性

例外狀況

valuenullvalue is null.

startIndexlength 小於零。startIndex or length is less than zero.

-或--or-

value + startIndex 指定的位址對於目前的平台而言太大,也就是位址計算溢位。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.

-或--or-

要初始化的新字串長度太大而無法配置。The length of the new string to initialize is too large to allocate.

value + startIndex 指定的位址小於 64K。The address specified by value + startIndex is less than 64K.

-或--or-

無法使用 String 初始化 value 的新執行個體,假設 value 是 ANSI 編碼。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.

valuestartIndexlength 共同指定了無效的位址。value, startIndex, and length collectively specify an invalid address.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

String(SByte*, Int32, Int32, Encoding)

重要

此 API 不符合 CLS 規範。

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置、長度和 Encoding 物件的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

public:
 String(System::SByte* value, int startIndex, int length, System::Text::Encoding ^ enc);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value, int startIndex, int length, System.Text.Encoding enc);
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string

參數

value
SByte*

8 位元帶正負號整數陣列的指標。A pointer to an array of 8-bit signed integers.

startIndex
Int32

開始位置在 value 內。The starting position within value.

length
Int32

value 內要使用的字元數。The number of characters within value to use.

enc
Encoding

物件,指定以 value 參考之陣列的編碼方式。An object that specifies how the array referenced by value is encoded. 如果 encnull,則假設使用 ANSI 編碼方式。If enc is null, ANSI encoding is assumed.

屬性

例外狀況

valuenullvalue is null.

startIndexlength 小於零。startIndex or length is less than zero.

-或--or-

value + startIndex 指定的位址對於目前的平台而言太大,也就是位址計算溢位。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.

-或--or-

要初始化的新字串長度太大而無法配置。The length of the new string to initialize is too large to allocate.

value + startIndex 指定的位址小於 64K。The address specified by value + startIndex is less than 64K.

-或--or-

無法使用 String 初始化 value 的新執行個體,假設 value 是依照 enc 的指定所編碼。A new instance of String could not be initialized using value, assuming value is encoded as specified by enc.

valuestartIndexlength 共同指定了無效的位址。value, startIndex, and length collectively specify an invalid address.

備註

注意

如需有關這個和其他 String 的函式多載的範例和完整使用方式資訊,請參閱 String 的檢查程式摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

適用於