日期:2014-05-18  浏览次数:20839 次

C#中String类的构造函数是如何将char数组转换成字符串的
C# code

char[] c = new char[] { 'a','b','c','d'};
string s = new string(c);
 Console.WriteLine("{0}",s);



这里的 new string(c),字符数组传进去了,字符串出来了,内部怎么搞了一把呢?
不会是循环把若干个字符拼接起来了吧?

------解决方案--------------------
理论上说,先分配数组所有元素加起来内存空间,再把数组从头到尾拷贝到刚分配的空间里,让程序把那段内存空间当string 读出来
------解决方案--------------------
应该string类内部有个私有成员变量就是字符数组char[],把构造函数中的字符数组参数拷贝到内部数组中。
而ToString()才是把字符拼接显示出来。
另外,字符串的拼接应该是内部字符数组容量的扩充后拷贝。

------解决方案--------------------
C# code

[ComVisible(true)]
  [Serializable]
  public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
  {
    public static readonly string Empty = "";
    private const int TrimHead = 0;
    private const int TrimTail = 1;
    private const int TrimBoth = 2;
    private const int charPtrAlignConst = 1;
    private const int alignConst = 3;
    [NonSerialized]
    private int m_stringLength;
    [ForceTokenStabilization]
    [NonSerialized]
    private char m_firstChar;

    internal char FirstChar
    {
      get
      {
        return this.m_firstChar;
      }
    }

    [IndexerName("Chars")]
    public char this[int index] { [SecuritySafeCritical, MethodImpl(MethodImplOptions.InternalCall)] get; }

    public int Length { [SecuritySafeCritical, MethodImpl(MethodImplOptions.InternalCall)] get; }

    static String()
    {
    }

    [CLSCompliant(false)]
    [SecurityCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(char* value);

    [SecurityCritical]
    [CLSCompliant(false)]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(char* value, int startIndex, int length);

    [CLSCompliant(false)]
    [SecurityCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(sbyte* value);

    [CLSCompliant(false)]
    [SecurityCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(sbyte* value, int startIndex, int length);

    [SecurityCritical]
    [CLSCompliant(false)]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(sbyte* value, int startIndex, int length, Encoding enc);

    [SecuritySafeCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(char[] value, int startIndex, int length);

    [SecuritySafeCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(char[] value);

    [SecuritySafeCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    public String(char c, int count);

------解决方案--------------------
话说还有一种方式可以清晰的知道,.net你只能靠反编译,但是你可以去看.net的linux实现:mono的源代码,应该是类似的