拓展方法的定义及调用和微软拼音组件的使用

 我们在做拼音查询的时候可能会用到微软的拼音组件,我用到这个时候想到正好可以使用拓展方法,拓展给string。来和大家一起学习交流。

 下载地址:点击打开链接微软的拼音组件包里面有七个工具,我们用的是这个CHSPinYinConv.msi,双击安装,安装目录会产生一个dll,我们在工程里面添加引用就好,拓展方法的定义和使用在注释里面。下面看代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.International.Converters.PinYinConverter;//引入拼音组件空间

namespace pin_yinConvert
{
    public static class ExpansionMethod
    {
        //拓展方法必须在一个非嵌套、非泛型的静态类中,且一定是静态方法
        //拓展方法至少要有一个参数
        //拓展方法第一个参数必须加上this关键字作为前缀
        //拓展方法第一个参数类型也称为扩展类型(extended type),表示该方法对这个类型进行扩展
        //拓展方法第一个参数不能用this以外的修饰符(比如out或ref)
        //拓展方法第一个参数不能是指针类型

        /// <summary>
        /// string 的拓展方法,用于获取字符串中汉字的拼音
        /// </summary>
        /// <param name="chinese"></param>
        public static string getAllPinYin(this string chinese)
        {
            var py = "";
            foreach (char c in chinese)
            {
                if (c >= 0x4e00 && c <= 0x9fbb)//UNICODE 中 汉子的范围是:0x4e00 - 0x9fbb,以此来判断是否是中文
                {
                    ChineseChar chc = new ChineseChar(c);
                    //Pinyins 返回的是一个只读数组,如果是多音字,那么数组里面会有多个元素。每一个元素的格式是拼音加1到5的某一个数字,代表声调,5代表轻音,如:中-- ZHONG1/ZHONG4。
                    py += chc.Pinyins[0].Substring(0, chc.Pinyins[0].Length - 1) + " ";
                }
                else
                {
                    py += c + " ";
                }
            }

            return " '" + chinese + "' 的拼音是: " + py;
            //Console.WriteLine();
        }

        /// <summary>
        /// string 的拓展方法,用于获取汉字的首字母
        /// </summary>
        /// <param name="chinese"></param>
        /// <returns></returns>
        public static string getFirstPinYin(this string chinese)
        {
            var py = "";
            foreach (char c in chinese)
            {
                if (c >= 0x4e00 && c <= 0x9fbb)
                {
                    ChineseChar chc = new ChineseChar(c);
                    py += chc.Pinyins[0][0];
                }
                else
                {
                    return ""; //存在非汉字字符,直接结束
                }
            }
            return py;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //拓展方法的使用:

            //1、用拓展类型string,直接调用拓展方法。
            string chinese = "我是怀梦逆行";       
            Console.WriteLine(chinese.getAllPinYin());
            Console.WriteLine(chinese.getFirstPinYin());

            //2、用拓展方法所在的类(ExpansionMethod),调用
            Console.WriteLine(ExpansionMethod.getAllPinYin("我是怀梦逆行"));
            Console.WriteLine(ExpansionMethod.getFirstPinYin("我是怀梦逆行")); 
        }

        //PS:判断一个方法是拓展方法还是原生方法,vs中,鼠标悬停在上面会看到拓展方法有(extension) 修饰
    }
}




猜你喜欢

转载自blog.csdn.net/maaici/article/details/79116570
今日推荐