Is there any difference between UTF8Encoding.UTF8.GetBytes and Encoding.UTF8.GetBytes?
Today I saw a code in which UTF8Encoding.UTF8.GetBytes
and Encoding.U开发者_JAVA百科TF8.GetBytes
is used. Is there any difference between them?
No difference at all.
Encoding.UTF8
is UTF8Encoding
.
From MSDN (Encoding.UTF8
):
This property returns a UTF8Encoding object
Instead of Encoding.UTF8.GetBytes
you can simply call UTF8Encoding.GetBytes
.
There is at least one difference. Encoding.UTF8 will write BOM while UTF8Encoding will not (by default). Check this out:
using System;
using System.Text;
class UTF8EncodingExample {
public static void Main() {
UTF8Encoding utf8 = new UTF8Encoding();
UTF8Encoding utf8EmitBOM = new UTF8Encoding(true);
Console.WriteLine("utf8 preamble:");
ShowArray(utf8.GetPreamble());
Console.WriteLine("utf8EmitBOM:");
ShowArray(utf8EmitBOM.GetPreamble());
Console.WriteLine("Encoding.UTF8 preamble:");
ShowArray(Encoding.UTF8.GetPreamble());
}
public static void ShowArray(Array theArray) {
foreach (Object o in theArray) {
Console.Write("[{0}]", o);
}
Console.WriteLine();
}
}
UTF8Encoding inherits its static UTF8 property from Encoding, so they are in fact the same property.
These are just two different ways to access the UTF8Encoding
class and call its static member GetBytes
.
精彩评论