C# StringBuilder 和字节转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9106847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
StringBuilder and byte conversion
提问by R.Vector
I have the following code:
我有以下代码:
StringBuilder data = new StringBuilder();
for (int i = 0; i < bytes1; i++)
{
data.Append("a");
}
byte[] buffer = Encoding.ASCII.GetBytes(data);
But I get this error:
但我收到此错误:
cannot convert from 'System.Text.StringBuilder' to 'char[]' The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])' has some invalid arguments
cannot convert from 'System.Text.StringBuilder' to 'char[]' The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])' has some invalid arguments
采纳答案by Scott Smith
The following code will fix your issue.
以下代码将解决您的问题。
StringBuilder data = new StringBuilder();
for (int i = 0; i < bytes1; i++)
{ data.Append("a"); }
byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
The problem is that you are passing a StringBuilderto the GetBytesfunction when you need to passing the string result from the StringBuilder.
问题是,你是一个合格StringBuilder的GetBytes功能,当你需要从传递字符串结果StringBuilder。
回答by Allen Xia
try this:
尝试这个:
byte[] buffer = Encoding.ASCII.GetBytes(data.ToString().ToCharArray());
回答by roken
GetBytes doesn't accept a StringBuilder as a parameter. Use a string with data.ToString()
GetBytes 不接受 StringBuilder 作为参数。使用带有 data.ToString() 的字符串
byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
回答by Thit Lwin Oo
Please try this. StringBuilder is object.. from there, you have to get string value as follow.
请试试这个。StringBuilder 是对象.. 从那里,你必须得到字符串值如下。
byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
回答by FauChristian
ASCII is not a good encoding choice for text in this century. Web and mobile applications should be at least using UTF-8, and any other type of application that is supposed to work in a globalized business or social networking environment should too.
在本世纪,ASCII 不是一个好的文本编码选择。Web 和移动应用程序至少应该使用 UTF-8,任何其他类型的应用程序都应该在全球化的商业或社交网络环境中工作。
StringBuilder builder = new StringBuilder();
for (int i = 0; i < iLength; ++ i)
builder.Append("a");
byte[] bytesFromBuilder = Encoding.UTF8.GetBytes(builder.ToString());

