[System.Security.SecuritySafeCritical] // auto-generated unsafe public static String Copy (String str) { if (str==null) { throw new ArgumentNullException("str"); } Contract.Ensures(Contract.Result<String>() != null); Contract.EndContractBlock(); int length = str.Length; String result = FastAllocateString(length); fixed(char* dest = &result.m_firstChar) fixed(char* src = &str.m_firstChar) { wstrcpy(dest, src, length); } return result; }
[System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static String FastAllocateString(int length);
在自己代码中调用
var fastAllocate = typeof (string).GetMethods(BindingFlags.NonPublic | BindingFlags.Static) .First(x => x.Name == "FastAllocateString"); var newString = (string)fastAllocate.Invoke(null, new object[] {20}); Console.WriteLine(newString.Length); // 20
这样用了反射,性能并不好。