ToCharArray不會在其結尾處置0。所以,我認爲,鑑於這個問題,你可以嘗試實現,做更多的東西像這樣的擴展方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string test = "This is a test";
char[] testArr = test.ToPaddedCharArray(32);
for (int i = 0; i < testArr.Length; i++)
{
Console.WriteLine("{0} = {1}", testArr[i], (int)testArr[i]);
}
}
}
public static class MyExtensions
{
public static char[] ToPaddedCharArray(this String str, int length)
{
char[] arr = new char[length];
int minl = Math.Min(str.Length, length-1);
for (int i = 0; i < minl; i++)
{
arr[i] = str[i];
}
for (int i = minl; i < length; i++)
{
arr[minl] = (char)0;
}
return arr;
}
}
}
這將產生輸出:
T = 84
h = 104
i = 105
s = 115
= 32
i = 105
s = 115
= 32
a = 97
= 32
t = 116
e = 101
s = 115
t = 116
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
= 0
Press any key to continue . . .
,你看到的是什麼垃圾? – Mrchief 2014-09-05 21:01:33
http://stackoverflow.com/questions/2996487/memcpy-function-in-c-sharp – MethodMan 2014-09-05 21:02:39
這是否工作? 'char [256] msg.name.Value =「This name \ 0」.ToCharArray();' – Dan 2014-09-05 21:04:59