为什么不从UTF8Encoding.GetBytes发出字节顺序标记?

xyz*_*xyz 13 .net c# unicode encoding utf-8

片段说明了一切:-)

UTF8Encoding enc = new UTF8Encoding(true/*include Byte Order Mark*/);
byte[] data = enc.GetBytes("a");
// data has length 1.
// I expected the BOM to be included. What's up?
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 18

你不希望它被用于每次调用GetBytes,否则你无法(比方说)一次写一行文件.

通过使用GetPreamble公开它,调用者可以在适当的位置(即在数据的开头)插入前导码.我同意文档可以更清楚.


xyz*_*xyz 9

谢谢你们俩.以下工作,LINQ使组合简单:-)

UTF8Encoding enc = new UTF8Encoding(true);
byte[] data = enc.GetBytes("a");
byte[] combo = enc.GetPreamble().Concat(data).ToArray();
Run Code Online (Sandbox Code Playgroud)