参考资料
https://blog.csdn.net/u011127019/article/details/99629697
(1)C# 的所有源代码文件,默认编码为 UTF-8,注意,是源代码文件,而不是 C# 中的 string。
(2)C# 中的所有 string,默认编码均为 Unicode (UTF-16)。
(3)C# 产生的 ASP.NET 源代码,如 ASPX/CS,在浏览器响应回去客户端之后,编码默认为 UTF-8。可以通过 ContentType 请求头信息更改默认编码。比如:ContentType: application/json, charset=utf-8。
(4)C# 中可以用 System.Text.Encoding.ASCII 提供的相关方法,把默认 Unicode 编码的字符串转换为 ASCII。详细请参考 GetString,GetBytes,GetByteCount 等方法。
测试过程
代码
1 public static string TestCoder() 2 { 3 string msg = "测试ceshi";//7个字符 4 StringBuilder sbContent = new StringBuilder(); 5 6 Dictionary<int, byte[]> pairs = new Dictionary<int, byte[]>(); 7 8 byte[] b1 = Encoding.ASCII.GetBytes(msg); 9 byte[] b2 = Encoding.Default.GetBytes(msg); 10 byte[] b3 = Encoding.UTF7.GetBytes(msg); 11 byte[] b4 = Encoding.UTF8.GetBytes(msg); 12 byte[] b5 = Encoding.Unicode.GetBytes(msg); 13 byte[] b6 = Encoding.BigEndianUnicode.GetBytes(msg); 14 byte[] b7 = Encoding.UTF32.GetBytes(msg); 15 16 pairs.Add(pairs.Count, b1); 17 pairs.Add(pairs.Count, b2); 18 pairs.Add(pairs.Count, b3); 19 pairs.Add(pairs.Count, b4); 20 pairs.Add(pairs.Count, b5); 21 pairs.Add(pairs.Count, b6); 22 pairs.Add(pairs.Count, b7); 23 24 foreach (KeyValuePair<int, byte[]> item in pairs) 25 { 26 sbContent.AppendLine(""); 27 string s1 = Encoding.ASCII.GetString(item.Value); 28 string s2 = Encoding.Default.GetString(item.Value); 29 string s3 = Encoding.UTF7.GetString(item.Value); 30 string s4 = Encoding.UTF8.GetString(item.Value); 31 string s5 = Encoding.Unicode.GetString(item.Value); 32 string s6 = Encoding.BigEndianUnicode.GetString(item.Value); 33 string s7 = Encoding.UTF32.GetString(item.Value); 34 35 int coder = item.Key; 36 string codeName = ""; 37 switch (coder) 38 { 39 case 0: codeName = "ASCII"; break; 40 case 1: codeName = "Default"; break; 41 case 2: codeName = "UTF7"; break; 42 case 3: codeName = "UTF8"; break; 43 case 4: codeName = "Unicode"; break; 44 case 5: codeName = "BigEndianUnicode"; break; 45 case 6: codeName = "UTF32"; break; 46 default: 47 break; 48 } 49 sbContent.AppendLine($"{coder}、编码方式:{codeName}".Replace("