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 位有符号整数数组的指针指示的值。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
处理重复的字符串 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 字符数组(U + 0000 或 "\ 0")终止的 Unicode 字符数组的指针指示的值。(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. 构造函数将从索引 startIndex 开始 value 的 Unicode 字符复制到索引 startIndex + length-1 (例如)。The constructor copies the Unicode characters from value starting at index startIndex and ending at index startIndex + length - 1 (example).

权限: SecurityCriticalAttribute,需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(SByte* value)
(不符合 CLS) 将新的实例初始化为由指向8位有符号整数数组的指针指示的值。(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 中处理的字符,直到达到空字符(例如)。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 开始处理值,并在 startIndex + length-1 (例如)结束。The constructor processes characters from value starting at startIndex and ending at startIndex + length - 1 (example).

权限: SecurityCriticalAttribute,需要直接调用方的完全信任。Permission: SecurityCriticalAttribute, requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(SByte* value, Int32 startIndex, Int32 length, Encoding enc)
(不符合 CLS) 将新的实例初始化为由指向8位有符号整数数组、该数组内的起始位置、长度和 Encoding 对象的指针指示的值。(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.Empty新对象的值。If count is zero, the value of the new object is String.Empty.

下面是包含指针参数 String 构造函数使用的参数的完整列表。Here is a complete list of parameters used by String constructors that include a pointer parameter. 对于每个重载使用的参数,请参阅上述重载语法。For the parameters used by each overload, see the overload syntax above.

参数Parameter 类型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 null 或空数组,则 String.Empty新字符串的值。If value is null or an empty array, the value of the new string is String.Empty.
startIndex Int32 数组元素的索引,该元素定义新字符串中的第一个字符。The index of the array element that defines the first character in the new string.

默认值:0Default value: 0
length Int32 用于创建新字符串的数组元素的数目。The number of array elements to use to create the new string. 如果 length 为零,则构造函数将创建一个字符串,其值为 String.EmptyIf length is zero, the constructor creates a string whose value is String.Empty.

默认值: Array.LengthDefault value: Array.Length
enc Encoding 一个对象,该对象指定如何对 value 数组进行编码。An object that specifies how the value array is encoded.

默认值: Encoding.Default或系统的当前 ANSI 代码页Default value: Encoding.Default, or the system's current ANSI code page

异常Exceptions

下面是不包含指针参数的构造函数引发的异常列表。Here's a list of exceptions thrown by constructors that don't include pointer parameters.

例外Exception 条件Condition 引发者Thrown by
ArgumentNullException valuenullvalue is null. String(Char[], Int32, Int32)
ArgumentOutOfRangeException startIndexlengthcount 小于零。startIndex,length, or count is less than zero.

-or-

startIndexlength 的和大于 value 中的元素数。The sum of startIndex and length is greater than the number of elements in value.

-or-

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

String(Char[], Int32, Int32)

下面是包含指针参数的构造函数引发的异常列表。Here's a list of exceptions thrown by constructors that include pointer parameters.

例外Exception 条件Condition 引发者Thrown by
ArgumentException value 指定包含无效 Unicode 字符的数组。value specifies an array that contains an invalid Unicode character.

-or-

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

-or-

无法从 value 字节数组初始化新的 String 实例,因为 value 不使用默认代码页编码。A new String instance could not be initialized from the value byte array because value does not use the default code page encoding.
带有指针的所有构造函数。All constructors with pointers.
ArgumentNullException value 为 null。value is null. String(SByte*)

String(SByte*, Int32, Int32)

String(SByte*, Int32, Int32, Encoding)
ArgumentOutOfRangeException 当前进程不具有对所有通过地址访问的字符的读取访问权限。The current process does not have read access to all the addressed characters.

-or-

startIndexlength 小于零,value + startIndex 导致指针溢出,或者当前进程不具有对所有寻址字符的读取访问权限。startIndex or length is less than zero, value + startIndex cause a pointer overflow, or the current process does not have read access to all the addressed characters.

-or-

新字符串的长度太大,无法分配。The length of the new string is too large to allocate.
带有指针的所有构造函数。All constructors with pointers.
AccessViolationException valuevalue + startIndex + length-1,则指定无效的地址。value, or value + startIndex + length - 1, specifies an invalid address. String(SByte*)

String(SByte*, Int32, Int32)

String(SByte*, Int32, Int32, Encoding)

我要调用哪种方法?Which method do I call?

功能To 调用或使用Call or use
创建一个字符串。Create a string. 从字符串文字或现有字符串赋值(示例Assignment from a string literal or an existing string (example)
从整个字符数组创建字符串。Create a string from an entire character array. String(Char[])示例String(Char[]) (example)
从字符数组的一部分创建字符串。Create a string from a portion of a character array. String(Char[], Int32, Int32)示例String(Char[], Int32, Int32) (example)
创建多次重复相同字符的字符串。Create a string that repeats the same character multiple times. String(Char, Int32)示例String(Char, Int32) (example)
从指向 Unicode 或宽字符数组的指针创建一个字符串。Create a string from a pointer to a Unicode or wide character array. String(Char*)
使用其指针从 Unicode 或宽字符数组的一部分创建字符串。Create a string from a portion of a Unicode or wide character array by using its pointer. String(Char*, Int32, Int32)
从C++ char 数组创建字符串。Create a string from a C++ char array. String(SByte*)String(SByte*, Int32, Int32)String(SByte*), String(SByte*, Int32, Int32)

-or-

String(SByte*, Int32, Int32, Encoding)
从 ASCII 字符创建一个字符串。Create a string from ASCII characters. ASCIIEncoding.GetString

创建字符串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 中的字符复制到索引 startIndex + length-1 到新字符串。The String(Char[], Int32, Int32) constructor copies the characters from index startIndex to index startIndex + length - 1 to the new string. 如果 length 为零,则 String.Empty新字符串的值。If length is zero, the value of the new string is String.Empty.

    如果你的代码重复实例化具有相同值的字符串,则可以使用创建字符串的替代方法来提高应用程序性能。If your code repeatedly instantiates strings that have the same value, you can improve application performance by using an alternate means of creating strings. 有关详细信息,请参阅处理重复的字符串For more information, see Handling repetitive strings.

  • 使用 String(Char, Int32) 构造函数从零次、一次或多次重复的单个字符。From a single character that is duplicated zero, one, or more times, by using the String(Char, Int32) constructor. 如果 count 为零,则 String.Empty新字符串的值。If count is zero, the value of the new string is String.Empty.

  • 通过使用 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,然后继续到数组末尾或 length 字符,复制一系列 Unicode 字符。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 字符的数组的指针传递到 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++中,这意味着必须将字符数组定义为托管 Char[] 类型或非托管wchar_t[] 类型。In C++, this means that the character array must be defined either as the managed Char[] type or the unmanagedwchar_t[] type.

    如果调用了 String(Char*) 重载,且数组不是以 null 终止的,或者如果 String(Char*, Int32, Int32) 重载被调用并且 startIndex + length-1 包括一个范围,该范围超出分配给字符序列的内存范围,构造函数的行为与系统相关,并可能会发生访问冲突。If the String(Char*) overload is called and the array is not null-terminated, or if the String(Char*, Int32, Int32) overload is called and startIndex + length-1 includes a range that it outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. 此外,在 Intel Itanium 处理器上,对 String(Char*, Int32, Int32) 构造函数的调用可能会引发 DataMisalignedException 异常。In addition, on the Intel Itanium processor, calls to the String(Char*, Int32, Int32) constructor may throw a DataMisalignedException exception. 如果出现这种情况,请改为调用 String(Char[], Int32, Int32)If this occurs, call the String(Char[], Int32, Int32) instead.

  • 从指向有符号字节数组的指针。From a pointer to a signed byte array. 整个数组或指定范围可用于初始化字符串。Either the entire array or a specified range can be used to initialize the string. 可以使用默认代码页编码来解释字节序列,也可以在构造函数调用中指定编码。The sequence of bytes can be interpreted by using the default code page encoding, or an encoding can be specified in the constructor call. 如果构造函数尝试从整个数组中实例化一个非 null 终止的字符串,或者从 + value的数组范围startIndexvalue + startIndex + 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 字符的数组的指针传递到 String(SByte*, Int32, Int32) 方法时,将发生的情况。The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the String(SByte*, Int32, Int32) method. 由于地址是数组的开头,数组中的所有元素都将添加到字符串,因此构造函数将实例化包含10个字符的字符串,包括两个嵌入的 null。Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. 另一方面,如果将同一个数组传递到 String(SByte*) 构造函数,则结果是一个四个字符的字符串,该字符串不包含第一个 null 字符。On the other hand, if the same array is passed to the String(SByte*) constructor, the result is a four-character string that does not include the first null character.

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

    由于 String(SByte*)String(SByte*, Int32, Int32) 构造函数使用默认的 ANSI 代码页来解释 value,因此使用相同的字节数组调用这些构造函数可能会在不同系统上创建具有不同值的字符串。Because the String(SByte*) and String(SByte*, Int32, Int32) constructors interpret value by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems.

处理重复的字符串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 对象即可保存通常出现的字符串。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) 方法将标记插入到表中,并获取相应的字符串。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(SByte*) 构造函数创建 String 类的实例。The following example demonstrates how you can create an instance of the String class with the String(SByte*) constructor.

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

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

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

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

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

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

版本信息Version information

.NET Framework.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*)

重要

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

指向以 null 终止的 Unicode 字符数组的指针。A pointer to a null-terminated array of Unicode characters.

属性

异常

当前进程不具有对所有通过地址访问的字符的读取访问权限。The current process does not have read access to all the addressed characters.

value 指定的数组包含无效的 Unicode 字符,或 value 指定的地址小于 64000。value specifies an array that contains an invalid Unicode character, or value specifies an address less than 64000.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(Char[])

String 类的新实例初始化为指定字符数组中指示的 Unicode 字符。Initializes a new instance of the String class to the Unicode characters indicated in the specified character array.

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

参数

value
Char[]

Unicode 字符的数组。An array of Unicode characters.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(ReadOnlySpan<Char>)

String 类的新实例初始化为指定只读范围中指示的 Unicode 字符。Initializes a new instance of the String class to the Unicode characters indicated in the specified read-only span.

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

参数

value
ReadOnlySpan<Char>

Unicode 字符的只读范围。A read-only span of Unicode characters.

String(SByte*)

重要

此 API 不符合 CLS。

String 类的新实例初始化为由指向 8 位有符号整数数组的指针指示的值。Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

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

参数

value
SByte*

一个指针,指向以 null 结尾的 8 位带符号整数数组。A pointer to a null-terminated array of 8-bit signed integers. 使用当前系统代码页编码(即由 Default 指定的编码)来解释整数。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).

属性

异常

valuenullvalue is null.

如果 value 采用 ANSI 进行编码,那么无法使用 value 初始化 String 的新实例。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.

要初始化的新字符串的长度(该长度由 value 的 null 终止字符确定)太大,无法分配。The length of the new string to initialize, which is determined by the null termination character of value, is too large to allocate.

value 指定的地址无效。value specifies an invalid address.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(Char, Int32)

String 类的新实例初始化为由重复指定次数的指定 Unicode 字符指示的值。Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

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

参数

c
Char

一个 Unicode 字符。A Unicode character.

count
Int32

c 出现的次数。The number of times c occurs.

异常

count 小于零。count is less than zero.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(Char*, Int32, Int32)

重要

此 API 不符合 CLS。

String 类的新实例初始化为由指向 Unicode 字符数组的指定指针指示的值、该数组内的起始字符位置和一个长度指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

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

参数

value
Char*

指向 Unicode 字符数组的指针。A pointer to an array of Unicode characters.

startIndex
Int32

value 内的起始位置。The starting position within value.

length
Int32

要使用的 value 内的字符数。The number of characters within value to use.

属性

异常

startIndexlength 小于零,value + startIndex 导致指针溢出,或者当前进程不具有对所有寻址字符的读取访问权限。startIndex or length is less than zero, value + startIndex cause a pointer overflow, or the current process does not have read access to all the addressed characters.

value 指定的数组包含无效的 Unicode 字符,或 value + startIndex 指定的地址小于 64000。value specifies an array that contains an invalid Unicode character, or value + startIndex specifies an address less than 64000.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(Char[], Int32, Int32)

String 类的新实例初始化为由 Unicode 字符数组、该数组内的起始字符位置和一个长度指示的值。Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

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

参数

value
Char[]

Unicode 字符的数组。An array of Unicode characters.

startIndex
Int32

value 内的起始位置。The starting position within value.

length
Int32

要使用的 value 内的字符数。The number of characters within value to use.

异常

valuenullvalue is null.

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

-or- startIndexlength 的和大于 value 中的元素数。The sum of startIndex and length is greater than the number of elements in value.

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

String(SByte*, Int32, Int32)

重要

此 API 不符合 CLS。

String 类的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置和一个长度指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

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

参数

value
SByte*

指向 8 位带符号整数数组的指针。A pointer to an array of 8-bit signed integers. 使用当前系统代码页编码(即由 Default 指定的编码)来解释整数。The integers are interpreted using the current system code page encoding (that is, the encoding specified by Default).

startIndex
Int32

value 内的起始位置。The starting position within value.

length
Int32

要使用的 value 内的字符数。The number of characters within value to use.

属性

异常

valuenullvalue is null.

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

-or- value + startIndex 指定的地址对于当前平台而言太大;也就是说,此地址计算溢出。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.

-or- 要初始化的新字符串的长度太大,无法分配。The length of the new string to initialize is too large to allocate.

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

-or- 如果 value 采用 ANSI 进行编码,那么无法使用 value 初始化 String 的新实例。A new instance of String could not be initialized using value, assuming value is encoded in ANSI.

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

注解

备注

有关此函数和其他 String 构造函数重载的示例和综合用法信息,请参阅 String 构造函数摘要。For examples and comprehensive usage information about this and other String constructor overloads, see the String constructor summary.

安全性

SecurityCriticalAttribute
需要对直接调用方的完全信任。requires full trust for the immediate caller. 部分受信任的或透明的代码不能使用此成员。This member cannot be used by partially trusted or transparent code.

String(SByte*, Int32, Int32, Encoding)

重要

此 API 不符合 CLS。

String 的新实例初始化为由指向 8 位有符号整数数组的指定指针、该数组内的起始位置、长度以及 Encoding 对象指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

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

参数

value
SByte*

指向 8 位带符号整数数组的指针。A pointer to an array of 8-bit signed integers.

startIndex
Int32

value 内的起始位置。The starting position within value.

length
Int32

要使用的 value 内的字符数。The number of characters within value to use.

enc
Encoding

一个对象,用于指定如何对 value 所引用的数组进行编码。An object that specifies how the array referenced by value is encoded. 如果 encnull,则假定以 ANSI 编码。If enc is null, ANSI encoding is assumed.

属性

异常

valuenullvalue is null.

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

-or- value + startIndex 指定的地址对于当前平台而言太大;也就是说,此地址计算溢出。The address specified by value + startIndex is too large for the current platform; that is, the address calculation overflowed.

-or- 要初始化的新字符串的长度太大,无法分配。The length of the new string to initialize is too large to allocate.

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

-or- 如果 value 按照指定的 enc 进行编码,那么无法使用 value 初始化 String 的新实例。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.

适用于