Encoding.UTF8.GetBytes和UTF8Encoding.Default.GetBytes的区别 [英] Difference between Encoding.UTF8.GetBytes and UTF8Encoding.Default.GetBytes

查看:5143
本文介绍了Encoding.UTF8.GetBytes和UTF8Encoding.Default.GetBytes的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能请解释一下我什么区别赌注。 Encoding.UTF8.GetBytes和UTF8Encoding.Default.GetBytes?其实我想一个XML字符串转换成流对象,现在情况是,每当我用这个行:

Can someone please explain me what is the difference bet. Encoding.UTF8.GetBytes and UTF8Encoding.Default.GetBytes? Actually I am trying to convert a XML string into a stream object and what happens now is whenever I use this line:

  MemoryStream stream = new MemoryStream(UTF8Encoding.Default.GetBytes(xml));



它给了我一个错误System.Xml.XmlException:无效字符在给定的编码

it gives me an error "System.Xml.XmlException: Invalid character in the given encoding"

但是当我使用这条线正常工作:

but when I use this line it works fine:

  **MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));**

虽然看上去要在这两种情况下UTF8编码怎么一工程和其他不?

Even though it seems to be UTF8 encoding in both cases how one works and the other does not?

推荐答案

有没有 UTF8Encoding.Default 属性。当你写这篇文章,你实际上返回基类的静态属性, Encoding.Default ,这不是UTF8(这是系统的默认ANSI代码页的编码)。

There is no UTF8Encoding.Default property. When you write this, you're actually returning the base class static property, Encoding.Default, which is not UTF8 (it's the system's default ANSI code-page encoding).

因此,两人将返回截然不同的结果 - 因为 UTF8Encoding.Default 其实就是 Encoding.Default ,您将返回因为如果你使用同样的事情 ASCIIEncoding.Default 或任何其它 System.Text.Encoding 子类。

As such, the two will return very different results - since UTF8Encoding.Default is actually Encoding.Default, you will return the same thing as if you use ASCIIEncoding.Default or any of the other System.Text.Encoding subclasses.

使用 UTF8Encoding 是您创建一个实例,如正确的方法:

The proper way to use UTF8Encoding is with an instance you create, such as:

MemoryStream stream = new MemoryStream((new UTF8Encoding()).GetBytes(xml));



上面应该提供相同的结果:

The above should provide the same results as:

MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));

这篇关于Encoding.UTF8.GetBytes和UTF8Encoding.Default.GetBytes的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆