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

多載的函式語法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 # 需要使用指標在 unsafe 內容中執行的程式碼。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 索引處開始複製 Unicode 字元 startIndex ,並在索引 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位帶正負號整數陣列的指標所指示的值。(Not CLS-compliant) Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. 陣列會假設為使用目前的系統字碼頁編碼的字串 (也就是) 指定的編碼方式 Encoding.DefaultThe array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by Encoding.Default). 此函式會處理從 value 指標所指定的位置開始的字元,直到達到 null 字元 (0x00) (範例) 為止。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.DefaultThe 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 (範例) 的值開始的字元。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.

以下是包含指標參數的函式所使用之參數的完整清單 StringHere 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. 如果 valuenull 或空陣列,則新字串的值為 String.EmptyIf 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. 如果長度為零,則此函式會建立其值為的字串 String.EmptyIf length is zero, the constructor creates a string whose value is String.Empty.

預設值:Array.LengthDefault value: Array.Length
enc Encoding 指定如何編碼陣列的物件 valueAn 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-

String無法從位元組陣列初始化新的實例, value 因為 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 + + 陣列建立字串 charCreate 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 -1 複製到 startIndex + length 新字串。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.

  • 使用或函式,從以 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 ,然後繼續進行陣列或字元的結尾 lengthThe 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 is outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur.

  • 從帶正負號位元組陣列的指標。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 結束的整個陣列中具現化字串,或從到-1 的陣列範圍超出配置給 value + startIndex value + startIndex + length 陣列的記憶體,則此函式的行為會與系統相依,而且可能會發生存取違規。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.

處理重複的字串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 物件來保存經常發生的字串,而不需要將每個標記轉換成新的字串。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. 如果 token 存在,方法會傳回對應的字串。If the token exists, the method returns the corresponding string. 如果權杖不存在,請使用 NameTable.Add(Char[], Int32, Int32) 方法將權杖插入資料表中,並取得對應的字串。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. 這些是具現化新物件的兩個最常見方式 StringThese 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 # 範例必須使用編譯器參數來編譯 /unsafeThe 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 # 範例必須使用編譯器參數來編譯 /unsafeThe 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 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") );
}

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

適用於

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);
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)]
public String (sbyte* value);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public String (sbyte* value);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
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.

無法使用 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.

適用於

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

適用於

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

無法使用 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.

適用於

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)]
public String (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);
[<System.CLSCompliant(false)>]
new string : nativeptr<sbyte> * int * int * System.Text.Encoding -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
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-

無法使用 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.

適用於