.net C# Unicode 字符串输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5055659/
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
C# Unicode string output
提问by Reg
I have a function to convert a string to a Unicode string:
我有一个将字符串转换为 Unicode 字符串的函数:
private string UnicodeString(string text)
{
return Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(text));
}
But when I am calling this function the output result is wrong. It looks like my function is not working.
但是当我调用这个函数时,输出结果是错误的。看起来我的功能不起作用。
Console.WriteLine(UnicodeString("добры дзень"))printing on console just questions like that: ????? ????
Console.WriteLine(UnicodeString("добры дзень"))在控制台上打印只是这样的问题: ????? ????
Is there a way to say to console to display it correct?
有没有办法让控制台正确显示它?
UPDATE
更新
It looks like the problem not in Unicode. I think maybe it is displaying question marks because I am not having the correct locale in the system (Windows 7)?
看起来问题不在 Unicode 中。我想也许它显示问号是因为我在系统中没有正确的语言环境(Windows 7)?
Is there a way to make it work without changing locale?
有没有办法让它在不改变语言环境的情况下工作?
回答by Kobi
First, change the output encoding to UTF8:
首先,将输出编码更改为UTF8:
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("добры дзень");
Now you'll still see question marks. The reason is that the default console's font doesn't support Cyrillic letters. Change the font of the console:
现在你仍然会看到问号。原因是默认控制台的字体不支持 Cyrillic 字母。更改控制台的字体:


If you're lucky, you should find a different font with Unicode support:
如果幸运的话,您应该会找到一种支持 Unicode 的不同字体:


Change the font, and you should be able to see your text:
更改字体,您应该能够看到您的文本:


In the general case, if you want to display all Unicode characters reliably, the Console is probably not right for you. See also: C# console font(the comments are interesting too)
在一般情况下,如果您想可靠地显示所有 Unicode 字符,控制台可能不适合您。另请参阅:C# 控制台字体(注释也很有趣)
回答by Albin Sunnanbo
private string UnicodeString(string text)
{
return text;
}
The string textis already in Unicode. All internal C# strings are Unicode. When you convert it to ASCII you lose characters. That is why you get ????? ????.
该字符串text已经是 Unicode。所有内部 C# 字符串都是 Unicode。当您将其转换为 ASCII 时,您会丢失字符。这就是为什么你得到????????.
回答by EliotVU
Just do plain simple Console.WriteLine("добры дзень");no need for any conversion.
只需做简单的事情,Console.WriteLine("добры дзень");不需要任何转换。

