0

为了在 .NET 上做得更好,我发现了解 .Net-Framework 本身以及 Microsoft 如何实现所有美好的东西很有帮助。上次我使用我的反编译器查看 的实现System.String-Class,研究 String-Object 如何存储其实际字符串。我对 self 中最大的类感到惊讶,并且我无法清楚地确定实际字符串保存的类的哪一部分。

这是反编译的两个屏幕截图,显示了类的开始和结束部分: 在此处输入图像描述 在此处输入图像描述

我想[System.Reflection.DefaultMember("Chars")](第一个屏幕截图的第一行)和/或属性public extern char this[int index](第二个屏幕截图的中间)是我正在寻找的。

这是正确的,如果是的话,它是如何工作的?

4

1 回答 1

4

System.String is a very special type. It's the only type in .NET other than arrays where different instances can have different sizes. (Anything else which "appears" to have different sizes such as List<T> usually depends on an array, or some recursive type like a LinkedList node. The objects themselves are of a fixed size.) The character data is inline within the object itself, along with the length of the string. It's not like a String holds a reference to a char[] or similar.

The CLR has very deep knowledge of System.String, and a lot of it is implemented in native code. Basically, I would recommend against trying to understand the implementation at this point - it's likely to be more confusing than helpful.

The Chars member (the indexer in C#) only fetches a single character from the string. You could follow that to find out more about where the data is stored, but it doesn't perform the actual storage itself.

于 2013-04-29T06:26:30.037 回答