UTF8Encoding.GetMaxCharCount(Int32) 方法

定义

计算对指定数目的字节进行解码时产生的最大字符数。

public:
 override int GetMaxCharCount(int byteCount);
public override int GetMaxCharCount (int byteCount);
override this.GetMaxCharCount : int -> int
Public Overrides Function GetMaxCharCount (byteCount As Integer) As Integer

参数

byteCount
Int32

要解码的字节数。

返回

Int32

对指定数目的字节进行解码时所产生的最大字符数。

例外

byteCount 小于零。

  • 或 - 得到的字节数大于可作为整数返回的最大数量。

发生回退(有关详细信息,请参阅采用 .NET 的字符编码) -和- 将 DecoderFallback 设置为 DecoderExceptionFallback

示例

以下示例使用 GetMaxCharCount 该方法返回通过解码指定字节数生成的最大字符数。

using namespace System;
using namespace System::Text;
int main()
{
   UTF8Encoding^ utf8 = gcnew UTF8Encoding;
   int byteCount = 8;
   int maxCharCount = utf8->GetMaxCharCount( byteCount );
   Console::WriteLine( "Maximum of {0} characters needed to decode {1} bytes.", maxCharCount, byteCount );
}
using System;
using System.Text;

class UTF8EncodingExample {
    public static void Main() {
        UTF8Encoding utf8 = new UTF8Encoding();
        int byteCount = 8;
        int maxCharCount = utf8.GetMaxCharCount(byteCount);
        Console.WriteLine(
            "Maximum of {0} characters needed to decode {1} bytes.",
            maxCharCount,
            byteCount
        );
    }
}
Imports System.Text

Class UTF8EncodingExample
    
    Public Shared Sub Main()
        Dim utf8 As New UTF8Encoding()
        Dim byteCount As Integer = 8
        Dim maxCharCount As Integer = utf8.GetMaxCharCount(byteCount)
        Console.WriteLine( _
            "Maximum of {0} characters needed to decode {1} bytes.", _
            maxCharCount, _
            byteCount _
        )
    End Sub
End Class

注解

若要计算存储生成的字符所需的 GetChars 确切数组大小,请调用 GetCharCount 该方法。 若要计算最大数组大小,请调用 GetMaxCharCount 该方法。 该方法 GetCharCount 通常分配较少的内存,而 GetMaxCharCount 该方法通常执行速度更快。

GetMaxCharCount 是一个最差的数字,包括当前所选 DecoderFallback的最坏情况。 如果使用可能较大的字符串选择回退, GetMaxCharCount 可以返回大值。

在大多数情况下,此方法返回小字符串的合理数字。 对于大型字符串,可能需要在极少数情况下选择使用非常大的缓冲区和捕获错误,即超出更合理的缓冲区。 你可能还需要考虑使用或的其他方法 GetCharCount Encoder.Convert

GetMaxCharCount与之间没有关系 GetBytes 。 如果应用程序需要使用类似的函数, GetBytes则应使用它 GetMaxByteCount

备注

GetMaxCharCount(N)不一定与相同 N* GetMaxCharCount(1)

适用于

另请参阅