简体   繁体   English

用C#编码字符

[英]Encoding for characters in C#

I'm studying alone from a book. 我正在独自读书。 In the book it is said that I can use all symbols that are in the Unicode table (although it is not explained very well). 在书中,我可以使用Unicode表中的所有符号(尽管并没有很好地解释它)。 But somehow I can't do it. 但是不知何故我做不到。 Here is the code that I test: 这是我测试的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            char a = '\u2605';
            Console.WriteLine(a);
        }
    }
}

The code should print a star, but the output is 该代码应打印一个星号,但输出为

" E" “ E”

Can you tell me how I can use any symbol from the table with no problems? 您能告诉我如何毫无问题地使用表格中的任何符号吗?

It is Unicode encoding you are looking for: 您正在寻找的是Unicode编码:

Console.OutputEncoding = System.Text.Encoding.Unicode;

As mentioned, it will only work if the console supports Unicode. 如前所述,只有在控制台支持Unicode的情况下,它才有效。 Also, the font used also needs to support the Unicode characters in order to display them. 此外,所使用的字体还需要支持Unicode字符才能显示它们。 For instance, Lucida Console does not support U+2605 , but it does support other characters . 例如, Lucida Console 支持U+2605 ,但它不支持其它字符

Console.OutputEncoding = System.Text.Encoding.Unicode;
char a = '\u2191';
Console.WriteLine(a);

The above code will print an upwards arrow in my console using either Consolas , Lucida Console or Raster Fonts . 上面的代码将使用ConsolasLucida ConsoleRaster Fonts在我的控制台中打印一个向上的箭头。

我很确定您需要先将char转换为字符串,然后尝试

Console.WriteLine(a.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM