gpt4 book ai didi

c# - C#中字符串的内部表示

转载 作者:太空狗 更新时间:2023-10-29 22:05:25 25 4
gpt4 key购买 nike

我只想确定:

string x = "";   
char Char = x[0]; // throws exception: "Index was outside the bounds of the array"

这意味着该字符串实际上被视为一个字符数组,对吗? (至少在内部。)

最佳答案

C# 语言规范不保证字符串的内部表示。但是,它实现了索引运算符,为字符串中的每个字符提供一个字符。

编辑:澄清一下,因为有几个人发表了评论,是的,CLR 中 System.String 的内部表示是一个数组。然而,语言规范没有说明任何关于内部表示的内容,所以这可能(但不太可能)改变。它说一个字符串必须作为一个字符序列来工作。语言规范中关于此的唯一一点是在第 1.3 节下:

Character and string processing in C# uses Unicode encoding. The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units.

此外,MSDN状态:

A string is a sequential collection of Unicode characters that is used to represent text. A String object is a sequential collection of System.Char objects that represent a string. The value of the String object is the content of the sequential collection, and that value is immutable (that is, it is read-only).

所以在这种情况下,我们现在谈论的是 CLR 而不是语言。 System.String -- 然而,即使在那里,它们也不能保证数组,只能保证顺序集合。

用链表和移动的索引器实现的字符串 n列表前面的空格足以满足语言要求。 IList<char>也将满足要求,并且IList不必由数组支持。

关于c# - C#中字符串的内部表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3787826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com