String String String String Constructors

定義

多載

String(Char*) String(Char*) 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(Char[]) String(Char[]) String(Char[])

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

String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>)
String(SByte*) String(SByte*) 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(Char, Int32) String(Char, Int32) 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(Char*, Int32, Int32) 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(Char[], Int32, Int32) String(Char[], Int32, Int32) 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(SByte*, Int32, Int32) 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(SByte*, Int32, Int32, Encoding) 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
處理重複的字串 Handling repetitive strings
具現化字串的範例:Examples of instantiating strings:
使用字串指派Using string assignment
使用字元陣列Using a character array
使用字元陣列的一部分並重複單一字元Using a portion of a character array and repeating a single character
使用字元陣列的指標Using a pointer to a character array
使用陣列的指標和範圍Using a pointer and a range of an array
使用帶正負號的位元組陣列的指標Using 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 字元陣列所指示的值。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 字元陣列、在該陣列內起始字元的位置,以及長度(範例)所指示的值。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 字元所指示的值,重複指定的次數(例如)。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 ')終止)。(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 字元陣列、在該陣列內起始字元的位置,以及長度的指標所指示的值。(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 startIndex處開始複製 Unicode 字元,並在索引 + 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位帶正負號整數陣列的指標所指示的值。(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位帶正負號整數的陣列、在該陣列內開始位置和長度的指標所指示的值。(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此函length式會處理從值開始,並從startIndex -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物件的指標所指示的值。(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 類型Type 說明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.EmptyIf 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 類型Type 說明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. 如果value String.Emptynull或空陣列,則新字串的值為。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.Empty的字串。If 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 + 指定小於 64k的位址。startIndexvalue or value + startIndex specifies an address that is less than 64K.

-或--or-

無法String value從位元組陣列初始化新的實例,因為不會使用預設字碼頁編碼。 valueA 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 value``value或-1length指定了不正確位址。 + startIndex + 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

建立字串Creating 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函式會將字元從索引length startIndex + -1 複製到新字串。The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length - 1 to the new string. 如果length為零,則新字串的值為String.EmptyIf 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.EmptyIf count is zero, the value of the new string is String.Empty.

  • 使用String(Char*)String(Char*, Int32, Int32)函式,從以 null 結束之字元陣列的指標。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. 此函式會從指定的指標或指定的指標加號startIndex開始複製 Unicode 字元序列,並繼續進行陣列的結尾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.Empty的字串。If 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.

    startIndex String(Char*, Int32, Int32) length + 如果呼叫多載且陣列不是以 null 終止,或呼叫多載,且-1 包含超出針對字元序列所配置之記憶體的範圍, String(Char*)此函式的行為與系統相關,而且可能會發生存取違規。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從到value + startIndex + startIndex + length -1 不在配置給陣列的記憶體之外,此函式的行為與系統相關,而且可能會發生存取違規。If 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)函式會value使用預設的 ANSI 字碼頁來解讀,因此以相同的位元組陣列呼叫這些函式,可能會在不同的系統上建立具有不同值的字串。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.

處理重複的字串Handling 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)方法來抓取資料表中的權杖。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: Using 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: Using 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: Using 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: Using 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: Instantiating 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: Instantiating a string from a pointer to a signed byte array

下列範例示範如何使用此String String(SByte*)函式來建立類別的實例。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.NET Framework
支援所有多載:4.5、4、3.5、3.0、2.0、1.1、1。0All overloads are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile.NET Framework Client Profile
支援所有多載:4,3.5 SP1All overloads are supported in: 4, 3.5 SP1

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

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

String(Char*) String(Char*) 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(Char[]) String(Char[]) String(Char[])

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

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(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>)

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

參數

String(SByte*) String(SByte*) 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).

例外狀況

無法使用 value 初始化 String 的新執行個體,假設 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(Char, Int32) String(Char, Int32) 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 Char Char Char

Unicode 字元。A Unicode character.

count
Int32 Int32 Int32 Int32

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

例外狀況

備註

注意

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

String(Char*, Int32, Int32) String(Char*, Int32, Int32) 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 Int32 Int32 Int32

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

length
Int32 Int32 Int32 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(Char[], Int32, Int32) String(Char[], Int32, Int32) 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 Int32 Int32 Int32

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

length
Int32 Int32 Int32 Int32

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

例外狀況

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) String(SByte*, Int32, Int32) 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 Int32 Int32 Int32

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

length
Int32 Int32 Int32 Int32

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

例外狀況

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- 無法使用 value 初始化 String 的新執行個體,假設 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) String(SByte*, Int32, Int32, Encoding) 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 Int32 Int32 Int32

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

length
Int32 Int32 Int32 Int32

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

enc
Encoding Encoding Encoding Encoding

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

例外狀況

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- 無法使用 value 初始化 String 的新執行個體,假設 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.

適用於