NET Framework 4.5新特性 (二) 控制台支持 Unicode (UTF-16) 编码

从 .NET Framework 4.5 开始,Console 类支持与 UnicodeEncoding 类的 UTF-16 编码。  显示 Unicode 字符到控制台,你可以设置 OutputEncoding 属性为 UTF8EncodingUnicodeEncoding

下面的示例显示 Unicode 字符的范围到控制台中。  该示例接受三个命令行参数:显示范围的开头,显示范围的末尾,以及是否使用当前控制台编码 (false) 或 UTF-16 编码 (true)。  假定控制台使用一个 TrueType 字体。

    class Program
    {
        private static void Main(string[] args)
        {
            uint rangeStart = 0;
            uint rangeEnd = 0;
            bool setOutputEncodingToUnicode = true;
            // Get the current encoding so we can restore it.
            Encoding originalOutputEncoding = Console.OutputEncoding;

            try
            {
                switch (args.Length)
                {
                    case 2:
                        rangeStart = uint.Parse(args[0], NumberStyles.HexNumber);
                        rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber);
                        setOutputEncodingToUnicode = true;
                        break;
                    case 3:
                        if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart))
                            throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0]));

                        if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd))
                            throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1]));

                        bool.TryParse(args[2], out setOutputEncodingToUnicode);
                        break;
                    default:
                        Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]",
                                          Environment.GetCommandLineArgs()[0],
                                          "startingCodePointInHex",
                                          "endingCodePointInHex",
                                          "<setOutputEncodingToUnicode?{true|false, default:false}>");
                        return;
                }

                if (setOutputEncodingToUnicode)
                {
                    // This won‘t work before .NET Framework 4.5.
                    try
                    {
                        // Set encoding using endianness of this system.
                        // We‘re interested in displaying individual Char objects, so
                        // we don‘t want a Unicode BOM or exceptions to be thrown on
                        // invalid Char values.
                        Console.OutputEncoding = new UnicodeEncoding(!BitConverter.IsLittleEndian, false);
                        Console.WriteLine("\nOutput encoding set to UTF-16");
                    }
                    catch (IOException)
                    {
                        Console.OutputEncoding = new UTF8Encoding();
                        Console.WriteLine("Output encoding set to UTF-8");
                    }
                }
                else
                {
                    Console.WriteLine("The console encoding is {0} (code page {1})",
                                      Console.OutputEncoding.EncodingName,
                                      Console.OutputEncoding.CodePage);
                }
                DisplayRange(rangeStart, rangeEnd);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Restore console environment.
                Console.OutputEncoding = originalOutputEncoding;
            }
        }

        public static void DisplayRange(uint start, uint end)
        {
            const uint upperRange = 0x10FFFF;
            const uint surrogateStart = 0xD800;
            const uint surrogateEnd = 0xDFFF;

            if (end <= start)
            {
                uint t = start;
                start = end;
                end = t;
            }

            // Check whether the start or end range is outside of last plane.
            if (start > upperRange)
                throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})",
                                                          start, upperRange));
            if (end > upperRange)
                throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})",
                                                          end, upperRange));

            // Since we‘re using 21-bit code points, we can‘t use U+D800 to U+DFFF.
            if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd))
                throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}",
                                                          start, end, surrogateStart, surrogateEnd));
            uint last = RoundUpToMultipleOf(0x10, end);
            uint first = RoundDownToMultipleOf(0x10, start);

            uint rows = (last - first) / 0x10;

            for (uint r = 0; r < rows; ++r)
            {
                // Display the row header.
                Console.Write("{0:x5} ", first + 0x10 * r);

                for (uint c = 0; c < 0x10; ++c)
                {
                    uint cur = (first + 0x10 * r + c);
                    if (cur < start)
                    {
                        Console.Write(" {0} ", Convert.ToChar(0x20));
                    }
                    else if (end < cur)
                    {
                        Console.Write(" {0} ", Convert.ToChar(0x20));
                    }
                    else
                    {
                        // the cast to int is safe, since we know that val <= upperRange.
                        String chars = Char.ConvertFromUtf32((int)cur);
                        // Display a space for code points that are not valid characters.
                        if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
                                                        UnicodeCategory.OtherNotAssigned)
                            Console.Write(" {0} ", Convert.ToChar(0x20));
                        // Display a space for code points in the private use area.
                        else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) ==
                                                       UnicodeCategory.PrivateUse)
                            Console.Write(" {0} ", Convert.ToChar(0x20));
                        // Is surrogate pair a valid character?
                        // Note that the console will interpret the high and low surrogate
                        // as separate (and unrecognizable) characters.
                        else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) ==
                                                     UnicodeCategory.OtherNotAssigned)
                            Console.Write(" {0} ", Convert.ToChar(0x20));
                        else
                            Console.Write(" {0} ", chars);
                    }

                    switch (c)
                    {
                        case 3:
                        case 11:
                            Console.Write("-");
                            break;
                        case 7:
                            Console.Write("--");
                            break;
                    }
                }

                Console.WriteLine();
                if (0 < r && r % 0x10 == 0)
                    Console.WriteLine();
            }
        }

        private static uint RoundUpToMultipleOf(uint b, uint u)
        {
            return RoundDownToMultipleOf(b, u) + b;
        }

        private static uint RoundDownToMultipleOf(uint b, uint u)
        {
            return u - (u % b);
        }

    }

演示结果

NET Framework 4.5新特性 (二) 控制台支持 Unicode (UTF-16) 编码

时间: 2024-08-05 04:06:58

NET Framework 4.5新特性 (二) 控制台支持 Unicode (UTF-16) 编码的相关文章

.Net Framework 各个版本新特性总结 (一)

.Net Framework 4.5 新特性 最近面试时又看到有问.Net Framework 新特性的问题,一时被问到了.平时也是拿起来就用,新版本出来了,新特性也就是瞄一眼,也没去仔细查看.这次干脆花点时间总(翻)结(译)一下各个版本相比上一版本带来的新特性.主要参考来源是MSDN,一下是原文链接: Reference: https://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx#core 嗯,我们就从4.5开始. 目录

NET Framework 4.5新特性 (三)64位平台支持大于2 GB大小的数组

64位平台.NET Framework数组限制不能超过2GB大小.这种限制对于需要使用到大型矩阵和向量计算的工作人员来说,是一个非常大问题. 无论RAM容量有多大有多少,一旦你使用大型矩阵和向量计算工作的时候,经常会抛出一个System.OutOfMemoryException异常,如下图所示: 参考程序 class Program { private static void Main(string[] args) { int arrysize = 150000000; var large=ne

NET Framework 4.5新特性 (一) 数据库的连接加密保护。

NET Framework 4.5 ado.net数据库连接支持使用SecureString内存流方式保密文本.  一旦使用这类操作,文本加密是私有不能共享的,并在不再需要时从计算机内存中删除.  SecureString此类不能被继承. 下面做了一些演示 private void Login_Click(object sender, EventArgs e) { //登录参数 string userName = Username.Text; SecureString password = se

JDK1.8新特性(二): Lambda表达式 (参数列表) -&gt; { } 和函数式接口@FunctionalInterface

Lambda表达式 二:简介 JDK的升级的目的有以下几个:增加新的功能.修复bug.性能优化.简化代码等几个方面,Lambda表达式就是属于简化代码,用于简化匿名实现类,提供一种更加简洁的写法.Lambda表达式在Swift语言中称之为代码块,Lambda表达式可以认为是一种特殊的接口,该接口必须只有一个抽象方法. 语法 (参数类型 参数名, 数参数类型 参数名2...) -> { // code }; 小括号()中的内容就是方法中的参数列表包括参数类型.参数名,其中参数类型是可以省略的,当参

Spark整合kafka0.10.0新特性(二)

接着Spark整合kafka0.10.0新特性(一)开始 import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.common.serialization.StringDeserializer import org.apache.spark.streaming.kafka010._ import org.apache.spark.streaming.kafka010.LocationStrat

类的加载、时机、反射、模板设计、jdk7/jdk8新特性(二十六)

1.类的加载概述和加载时机 * A:类的加载概述 * 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三步来实现对这个类进行初始化. * 加载 * 就是指将class文件读入内存,并为之创建一个Class对象.任何类被使用时系统都会建立一个Class对象. * 连接 * 验证 是否有正确的内部结构,并和其他类协调一致 * 准备 负责为类的静态成员分配内存,并设置默认初始化值 * 解析 将类的二进制数据中的符号引用替换为直接引用 * 初始化 就是我们以前讲过的初始化

JAVA 8 主要新特性 ----------------(二)JDK1.8优点概括

一.JDK1.8优点概括 1.速度更快 由于底层结构和JVM的改变,使得JDK1.8的速度提高. 2.代码更少(增加了新的语法 Lambda 表达式)          增加新特性Lambda表达式的内部类改造,使得代码在书写上变得更加简洁 3.强大的 Stream API 增加了核心功能,使得代码调用方式变得更加简洁 4.便于并行 5.最大化减少空指针异常 Optional 原文地址:https://www.cnblogs.com/liuyangfirst/p/10057578.html

010-jdk1.8版本新特性二-Optional类,Stream流

1.5.Optional类 1.定义 Optional 类是一个可以为null的容器对象.如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象. Optional 是个容器:它可以保存类型T的值,或者仅仅保存null.Optional提供很多有用的方法,这样我们就不用显式进行空值检测. Optional 类的引入很好的解决空指针异常. 2.声明 以下是一个 java.util.Optional<T> 类的声明: public final class Option

C# 6.0 新特性 (二)

自动属性初始化表达式 有过正确实现结构经验的所有 .NET 开发人员无疑都为一个问题所困扰:需要使用多少语法才能使类型固定不变(为 .NET 标准建议的类型).此问题实际上是只读属性存在的问题: 定义为只读的支持字段 构造函数内支持字段的初始化 属性的显式实现(而非使用自动属性) 返回支持字段的显式 getter 实现 所有这一切仅仅是为了“正确地”实现固定不变的属性.之后,此情况还会针对类型的所有属性重复发生.因此,正确操作需要比不堪一击的方法付出明显更多的努力.发布了自动属性初始化表达式(C