来自 Microsoft 文档的 C# String.Length

C# String.Length from Microsoft Documentation

Microsoft documentation states 这段代码将 return 7 个字符

The Length property returns the number of Char objects in this instance, not the number of Unicode characters.

string characters = "abc\u0000def";
Console.WriteLine(characters.Length);    // Displays 7

我需要一个函数来 return 作为结果 12,因为有 12 个不同的字符。我可以使用哪个功能?

您将不得不阻止编译器对文字的解释。这可以使用 @ 前缀来完成,如下所示:

var characters = @"abc\u0000def";

此字符串的 Length 属性 将 return 12,但字符串中将不再有实际的 unicode 字符。

C# 编译器会将 \u0000 替换为空字节。这意味着,在执行时,您的内存中将只有 7 个字符。

如果不想让编译器替换特殊字符,首先要转义反斜杠:

string characters = "abc\u0000def";
Console.WriteLine(characters.Length);    // Displays 12