厚积薄发,丰富的公用类库积累,助你高效进行系统开发(13)— 各种常用的辅助类2
admin
2023-08-02 16:37:12
0

俗话说,一个好汉十个帮,众人拾柴火焰高等都说明一个道理,有更多的资源,更丰富的积累,都是助你走向成功,走向顶峰的推动力。
本篇的公用类库的介绍主题是程序开发中常用到的一些辅助类,在帮助文档中归类到其他目录下面,本篇主要介绍有注册表的操作、反射操作、正则表达式操作、Zip压缩操作、AD操作、字符串Unicode转换操作等常见但有些凌乱的类库。
本篇继续继续整理优化已有的共用类库,并继续发表随笔介绍公用类库的接口方法以及详细使用操作,力求给自己继续优化,积攒更丰富的公用类库资源,加深了解的同时,也给大家展现公用类库好的方面。
1、 注册表操作辅助类RegistryHelper,通过默认指定注册表的前缀路径,减少调用复杂性。
1)辅助类提供的方法接口如下所示:

///     
/// 获取注册表项的值。如果该键不存在,则返回空字符串。    
///     
/// 注册表键    
/// 指定键返回的值    
public static string GetValue(string key)    

///     
/// 获取注册表项的值。如果该键不存在,则返回空字符串。    
///     
/// 注册表键的前缀路径    
/// 注册表键    
/// 指定键返回的值    
public static string GetValue(string softwareKey, string key)    

///     
/// 获取注册表项的值。如果该键不存在,则返回空字符串。    
///     
/// 注册表键的前缀路径    
/// 注册表键    
/// 开始的根节点(Registry.CurrentUser或者Registry.LocalMachine等)    
/// 指定键返回的值    
public static string GetValue(string softwareKey, string key, RegistryKey rootRegistry)    

///     
/// 保存键值到注册表    
///     
/// 注册表键    
/// 键的值内容    
/// 如果保存成功返回true,否则为false    
public static bool SaveValue(string key, string value)    

///     
/// 保存键值到注册表    
///     
/// 注册表键的前缀路径    
/// 注册表键    
/// 键的值内容    
/// 如果保存成功返回true,否则为false    
public static bool SaveValue(string softwareKey, string key, string value)    

///     
/// 保存键值到注册表    
///     
/// 注册表键的前缀路径    
/// 注册表键    
/// 键的值内容    
/// 开始的根节点(Registry.CurrentUser或者Registry.LocalMachine等)    
/// 如果保存成功返回true,否则为false    
public static bool SaveValue(string softwareKey, string key, string value, RegistryKey rootRegistry)   

#endregion   

#region 自动启动程序设置    

///     
/// 检查是否随系统启动    
///     
///     
public static bool CheckStartWithWindows()    

///     
/// 设置随系统启动    
///     
///     
public static void SetStartWithWindows(bool startWin)   

#endregion

2)辅助类的使用例子代码如下所示

private void btnRegistryHelper_Click(object sender, EventArgs e)    
{    
    string result = string.Empty;    
    result += \"使用RegistryHelper注册表访问辅助类:\" + \"\\r\\n\";    

    string softwareKey = @\"Software\\DeepLand\\OrderWater\";    
    bool sucess = RegistryHelper.SaveValue(softwareKey, \"Test\", DateTime.Now.ToString());    
    if (sucess)    
    {    
        result += RegistryHelper.GetValue(softwareKey, \"Test\") + \"\\r\\n\";    
    }    

    RegistryHelper.SaveValue(softwareKey, \"Test\", \"测试内容\", Microsoft.Win32.Registry.LocalMachine);    
    result += RegistryHelper.GetValue(softwareKey, \"Test\", Microsoft.Win32.Registry.LocalMachine);     

    MessageUtil.ShowTips(result);    
}

演示代码效果如下所示。

2、 反射操作辅助类ReflectionUtil,如获取或设置字段、属性的值等反射信息。
本辅助类主要是用来方便实现反射操作辅助类,如获取或设置字段、属性的值等反射信息。 在通用的赋值操作(属性或者字段)、执行方法或者需要获取特定对象属性的时候,就需要大量用到反射操作。
1)辅助类提供的方法接口如下所示:

#region 属性字段设置    
///     
/// 绑定标识    
///     
public static BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.Public |    
                        BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;    

///     
/// 执行方法    
///     
/// 对象实例    
/// 方法名称    
/// 参数    
///     
public static object InvokeMethod(object obj, string methodName, object[] args)    

///     
/// 设置对象实例的字段值    
///     
/// 对象实例    
/// 字段名称    
/// 字段值    
public static void SetField(object obj, string name, object value)    

///     
/// 获取对象实例的字段值    
///     
/// 对象实例    
/// 字段名称    
///     
public static object GetField(object obj, string name)    

///     
/// 获取对象实例的字段集合    
///     
/// 对象实例    
///     
public static FieldInfo[] GetFields(object obj)    

///     
/// 设置对象实例的属性值    
///     
/// 对象实例    
/// 属性名称    
/// 属性值    
public static void SetProperty(object obj, string name, object value)    

///     
/// 获取对象实例的属性值    
///     
/// 对象实例    
/// 属性名称    
///     
public static object GetProperty(object obj, string name)    

///     
/// 获取对象实例的属性列表    
///     
/// 对象实例    
///     
public static PropertyInfo[] GetProperties(object obj)    

///     
/// 把对象的属性和值,输出一个键值的字符串,如A=1&B=test    
///     
/// 实体对象    
/// 是否包含空白属性的键值    
///     
public static string ToNameValuePairs(object obj, bool includeEmptyProperties = true)   

#endregion   

#region 获取Description    

///     
/// 获取枚举字段的Description属性值    
///     
/// The value.    
/// return description or value.ToString()    
public static string GetDescription(Enum value)    

///     
/// Get The Enum Field Description using Description Attribute and     
/// objects to format the Description.    
///     
/// Enum For Which description is required.    
/// An Object array containing zero or more objects to format.    
/// return null if DescriptionAttribute is not found or return type description    
public static string GetDescription(Enum value, params object[] args)    

///     
/// 获取字段的Description属性值    
///     
/// Specified Member for which Info is Required    
/// return null if DescriptionAttribute is not found or return type description    
public static string GetDescription(MemberInfo member)    

///     
/// Get The Type Description using Description Attribute and     
/// objects to format the Description.    
///     
///  Specified Member for which Info is Required    
/// An Object array containing zero or more objects to format.    
/// return  if DescriptionAttribute is     
/// not found or return type description    
public static string GetDescription(MemberInfo member, params object[] args)   

#endregion   

#region 获取Attribute信息    

///     
/// 获取指定对象实例的attributes内容    
///     
/// The attribute Type for which the custom attributes are to be returned.    
/// the assembly in which the specified attribute is defined    
/// Attribute as Object or null if not found.    
public static object GetAttribute(Type attributeType, Assembly assembly)    

///     
/// 获取指定对象实例的attributes内容    
///     
/// The attribute Type for which the custom attributes are to be returned.    
/// the type on which the specified attribute is defined    
/// Attribute as Object or null if not found.    
public static object GetAttribute(Type attributeType, MemberInfo type)    

///     
/// Gets the specified object attributes for type as specified by type with option to serach parent    
///     
/// The attribute Type for which the custom attributes are to be returned.    
/// the type on which the specified attribute is defined    
/// if set to  [search parent].    
///     
/// Attribute as Object or null if not found.    
///     
public static object GetAttribute(Type attributeType, MemberInfo type, bool searchParent)    

///     
/// Gets the collection of all specified object attributes for type as specified by type    
///     
/// The attribute Type for which the custom attributes are to be returned.    
/// the type on which the specified attribute is defined    
/// Attribute as Object or null if not found.    
public static object[] GetAttributes(Type attributeType, MemberInfo type)    

///     
/// Gets the collection of all specified object attributes for type as specified by type with option to serach parent    
///     
/// The attribute Type for which the custom attributes are to be returned.    
/// the type on which the specified attribute is defined    
/// The attribute Type for which the custom attribute is to be returned.    
///     
/// Attribute as Object or null if not found.    
///     
public static object[] GetAttributes(Type attributeType, MemberInfo type, bool searchParent)   

#endregion   

#region 资源获取    

///     
/// 根据资源名称获取图片资源流    
///     
///     
///     
public static Stream GetImageResource(string ResourceName)    

///     
/// 获取程序集资源的位图资源    
///     
/// 程序集中的某一对象类型    
/// 资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。    
/// 资源项名称    
public static Bitmap LoadBitmap(Type assemblyType, string resourceHolder, string imageName)    

///     
///  获取程序集资源的文本资源    
///     
/// 程序集中的某一对象类型    
/// 资源项名称    
/// 资源的根名称。例如,名为“MyResource.en-US.resources”的资源文件的根名称为“MyResource”。    
public static string GetStringRes(Type assemblyType, string resName, string resourceHolder)    

///     
/// 获取程序集嵌入资源的文本形式    
///     
/// 程序集中的某一对象类型    
/// 字符集编码    
/// 嵌入资源相对路径    
/// 如没找到该资源则返回空字符    
public static string GetManifestString(Type assemblyType, string charset, string ResName)   

#endregion   

#region 创建对应实例    
///     
/// 创建对应实例    
///     
/// 类型    
/// 对应实例    
public static object CreateInstance(string type)    

///     
/// 创建对应实例    
///     
/// 类型    
/// 对应实例    
public static object CreateInstance(Type type)   

#endregion

2)辅助类的使用例子代码如下所示,例子是Socket框架里面用来反序列化对象的操作,通过反射把字符串的值赋值到对象里面。

///     
/// 转换Socket接收到的信息为对象信息    
///     
/// Socket接收到的信息    
public BaseEntity(string data)    
{    
    string[] dataArray = NetStringUtil.UnPack(data);    
    if (dataArray != null && dataArray.Length > 0)    
    {    
        int i = 0;    
        FieldInfo[] fieldArray = ReflectionUtil.GetFields(this);    
        if (fieldArray == null || dataArray.Length != fieldArray.Length)    
        {    
            throw new ArgumentException(\"收到的信息和字段信息不一致\");    
        }    

        if (fieldArray != null)    
        {    
            foreach (FieldInfo info in fieldArray)    
            {    
                string strValue = dataArray[i++];    
                try   
                {    
                    if (!string.IsNullOrEmpty(strValue))    
                    {    
                        ReflectionUtil.SetField(this, info.Name, strValue);    
                    }    
                }    
                catch (Exception ex)    
                {    
                    Communication.Model.Log.WriteError(string.Format(\"转换数据发生错误:{0}【{1}】\",    
                        ex.Message, data));    
                    break;    
                }    
            }    
        }    
    }    
}

例如两个对象的属性基本相同,可以进行对象的拷贝赋值。

#region 表结构一样,复制相关的内容    
PilotInfo pilotInfo = BLLFactory.Instance.FindByID(txtPilot.PilotID);    
if (pilotInfo != null)    
{    
    PropertyInfo[] outPropertyArray = ReflectionUtil.GetProperties(info);    
    PropertyInfo[] pilotPropArray = ReflectionUtil.GetProperties(pilotInfo);    
    if (pilotPropArray != null && outPropertyArray != null)    
    {    
        foreach (PropertyInfo propInfo in pilotPropArray)    
        {    
            try   
            {    
                object value = ReflectionUtil.GetProperty(pilotInfo, propInfo.Name);    
                foreach (PropertyInfo outInfo in outPropertyArray)    
                {    
                    if (outInfo.Name == propInfo.Name)    
                    {    
                        ReflectionUtil.SetProperty(info, propInfo.Name, value);    
                    }    
                }    
            }    
            catch (Exception ex)    
            {    
            }    
        }    
    }    
}   
#endregion

3、程序集反射创建对象实例辅助类 Reflect

本辅助类主要是用来方便实现程序集反射创建对象实例的操作。 该程序集反射春节对象实例的操作,在我的WInform开发框架中用于对象的创建操作。

1)辅助类提供的方法接口如下所示:

///     
/// 程序集反射创建对象实例辅助类    
///     
/// 对象类型    
public class Reflect where T : class     
{    
    ///     
    /// 缓存的hash表集合    
    ///     
    public static Hashtable ObjCache    

    ///     
    /// 根据参数创建对象实例    
    ///     
    /// 对象全局名称    
    /// 文件路径    
    ///     
    public static T Create(string sName, string sFilePath)    

    ///     
    /// 根据参数创建对象实例    
    ///     
    /// 对象全局名称    
    /// 文件路径    
    /// 缓存集合    
    ///     
    public static T Create(string sName, string sFilePath, bool bCache)    

    ///     
    /// 创建程序集对象    
    ///     
    /// 文件路径    
    ///     
    public static Assembly CreateAssembly(string sFilePath)    
}

2)辅助类的使用例子代码如下所示(摘自我的Winform开发框架里面的对象反射操作)。在下面的例子中,通过传入的类型T,在程序集中构造制定类型的对象,并放入到缓存当中。

public class BLLFactory where T : class   
{    
    private static Hashtable objCache = new Hashtable();    
    private static object syncRoot = new Object();    

    public static T Instance    
    {    
        get   
        {    
            string CacheKey = typeof(T).FullName;    
            T bll = (T)objCache[CacheKey];  //从缓存读取      
            if (bll == null)    
            {    
                lock (syncRoot)    
                {    
                    if (bll == null)    
                    {    
                        bll = Reflect.Create(typeof(T).FullName, \"WHC.WareHouseMis\"); //反射创建,并缓存    
                        //bll = Reflect.Create(typeof(T).FullName, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); //反射创建,并缓存    
                        objCache.Add(typeof(T).FullName, bll);    
                    }    
                }    
            }    
            return bll;    
        }    
    }    
}

4、 正则表达式辅助类 CRegex
本辅助类主要是用来方便实现对正则表达式的封装使用,通过利用该类库,可以简化C#对正则表达式的操作,但不能替代掌握正则表达式的知识。 正则表达式可以通过The Reguator等正则表达式调试工具来验证编写的表达式,基本的操作是匹配,替换,分割等,调试工具界面如下:

1)软件包含下面基础通用的操作正则表达式方法的定义,以及一些封装好的正则表达式操作,如获取HTML标题、Body等内容。

///     
/// 内容是否匹配指定的表达式    
///     
/// 输入内容    
/// 表达式字符串    
///     
public static bool IsMatch(string sInput, string sRegex)    

///     
/// 多个匹配内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 第几个分组, 从1开始, 0代表不分组    
public static List GetList(string sInput, string sRegex, int iGroupIndex)    

///     
/// 多个匹配内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 分组名, \"\"代表不分组    
public static List GetList(string sInput, string sRegex, string sGroupName)    

///     
/// 单个匹配内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 分组序号, 从1开始, 0不分组    
public static string GetText(string sInput, string sRegex, int iGroupIndex)    

///     
/// 单个匹配内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 分组名, \"\"代表不分组    
public static string GetText(string sInput, string sRegex, string sGroupName)    

///     
/// 替换指定内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 替换值    
/// 分组序号, 0代表不分组    
public static string Replace(string sInput, string sRegex, string sReplace, int iGroupIndex)    

///     
/// 替换指定内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 替换值    
/// 分组名, \"\" 代表不分组    
public static string Replace(string sInput, string sRegex, string sReplace, string sGroupName)    

///     
/// 分割指定内容    
///     
/// 输入内容    
/// 表达式字符串    
/// 最小保留字符串长度    
public static List Split(string sInput, string sRegex, int iStrLen)

5、 压缩文本、字节或者文件的压缩辅助类GZipUtil。

本辅助类主要是用来方便实现压缩文本、字节或者文件的压缩操作。本辅助类使用.NET内置的类库实现压缩操作。

1)辅助类提供的方法接口如下所示:

///     
/// 压缩字符串    
///     
/// 待压缩的文本    
/// 压缩后的文本内容    
public static string Compress(string text)    

///     
/// 解压字符串    
///     
/// 待解压缩的文本内容    
/// 解压后的原始文本内容    
public static string Decompress(string compressedText)    

///     
/// 压缩流对象    
///     
/// 对象类型    
/// 流数据    
/// 压缩类型    
///     
public static T GZip(Stream stream, CompressionMode mode) where T : Stream    

///     
/// 压缩字节    
///     
/// 待压缩字节    
/// 压缩后的字节数组    
public static byte[] Compress(byte[] bytData)    

///     
/// 解压字节    
///     
/// 待解压缩字节    
/// 解压后的原始字节内容    
public static byte[] Decompress(byte[] bytData)    

///     
/// 压缩Object对象到字节数组    
///     
/// 待压缩对象    
/// 压缩后的字节数组    
public static byte[] ObjectToGZip(object obj)    

///     
/// 从压缩的字节数组转换到Object对象    
///     
/// 待解压缩的字节数据    
/// 对象    
public static object GZipToObject(byte[] byteArray)    

///     
/// 压缩文件    
///     
/// 包括在zip文件中的文件夹路径,所有文件,包括子文件夹中的文件将包括在内。    
/// 写入到Zip文件的目标文件夹    
/// zip文件名称    
public static GZipResult Compress(string lpSourceFolder, string lpDestFolder, string zipFileName)    

///     
/// 压缩文件    
///     
/// 包括在zip文件中的源文件夹路径    
/// 搜索模式 (例如 \"*.*\" or \"*.txt\" or \"*.gif\") 以标识那些文件将被包含到Zip文件里面    
/// 指定是搜索当前目录,还是搜索当前目录及其所有子目录    
/// 写入zip目标文件夹的路径    
/// Zip文件名    
/// 布尔值,如果为true则删除中间临时文件,false则在lpDestFolder保留临时文件(调试用)    
public static GZipResult Compress(string lpSourceFolder, string searchPattern, SearchOption searchOption, string lpDestFolder, string zipFileName, bool deleteTempFile)    

///     
/// 压缩文件    
///     
/// 在zip文件中包含的FileInfo对象数组    
/// 文件夹字符串数组    
///     
/// 基础文件夹,在创建的zip文件中存储的文件的相对路径。例如, 如果lpBaseFolder 是 \'C:\\zipTest\\Files\\\',    
/// 当存在一个文件 \'C:\\zipTest\\Files\\folder1\\sample.txt\' 在数组\'files\'里面, 则 sample.txt 的相对路径是 \'folder1/sample.txt\'    
///     
/// 写入Zip文件的文件夹    
/// Zip文件名    
public static GZipResult Compress(FileInfo[] files, string[] folders, string lpBaseFolder, string lpDestFolder, string zipFileName)    

///     
/// 压缩文件    
///     
/// 在zip文件中包含的FileInfo对象数组    
///     
/// 基础文件夹,在创建的zip文件中存储的文件的相对路径。例如, 如果lpBaseFolder 是 \'C:\\zipTest\\Files\\\',    
/// 当存在一个文件 \'C:\\zipTest\\Files\\folder1\\sample.txt\' 在数组\'files\'里面, 则 sample.txt 的相对路径是 \'folder1/sample.txt\'    
///     
/// 写入Zip文件的文件夹    
/// Zip文件名    
public static GZipResult Compress(FileInfo[] files, string lpBaseFolder, string lpDestFolder, string zipFileName)    

///     
/// 压缩文件    
///     
/// 在zip文件中包含的FileInfo对象数组    
///     
/// 基础文件夹,在创建的zip文件中存储的文件的相对路径。例如, 如果lpBaseFolder 是 \'C:\\zipTest\\Files\\\',    
/// 当存在一个文件 \'C:\\zipTest\\Files\\folder1\\sample.txt\' 在数组\'files\'里面, 则 sample.txt 的相对路径是 \'folder1/sample.txt\'    
///     
/// 写入Zip文件的文件夹    
/// Zip文件名    
/// 布尔值,如果为true则删除中间临时文件,false则在lpDestFolder保留临时文件(调试用)    
public static GZipResult Compress(FileInfo[] files, string lpBaseFolder, string lpDestFolder, string zipFileName, bool deleteTempFile)    

///     
/// 解压文件    
///     
/// zip文件的源目录    
/// 解压到的目录    
/// Zip文件名    
///     
public static GZipResult Decompress(string lpSourceFolder, string lpDestFolder, string zipFileName)    

///     
/// 解压文件    
///     
/// zip文件的源目录    
/// 解压到的目录    
/// Zip文件名    
///     
/// 增加后缀名    
///     
public static GZipResult Decompress(string lpSourceFolder, string lpDestFolder, string zipFileName, bool writeFiles, string addExtension)    

///     
/// 解压文件    
///     
/// zip文件的源目录    
/// 解压到的目录    
/// Zip文件名    
/// 布尔值,如果为true则删除中间临时文件,false则在lpDestFolder保留临时文件(调试用)    
///     
/// 增加后缀名    
///     
///     
///     
public static GZipResult Decompress(string lpSrcFolder, string lpDestFolder, string zipFileName, bool deleteTempFile, bool writeFiles, string addExtension, Hashtable htFiles, int bufferSize)

2)辅助类的使用例子代码如下所示

//压缩解压缩文本内容    
string zippedContent = GZipUtil.Compress(\"wuhuacong\");    
string original = GZipUtil.Decompress(zippedContent);    

GZipUtil.Compress(Application.StartupPath, Application.StartupPath, \"cityroad.zip\");    
GZipUtil.Decompress(Application.StartupPath, Path.Combine(Application.StartupPath, \"cityroad\"), \"cityroad.zip\");    

MessageUtil.ShowTips(\"操作完成\");

6、字符串Unicode转换操作辅助类 UnicodeHelper。

1)辅助类提供的方法接口如下所示:

///     
/// 将原始字串转换为unicode,格式为\\u.\\u.    
///     
/// 待转换字符串    
///     
public static string StringToUnicode(string str)    

///     
/// 将Unicode字串\\u.\\u.格式字串转换为原始字符串    
///     
/// 待转换字符串    
///     
public static string UnicodeToString(string str)    

///     
/// GB2312转换成unicode编码     
///     
/// 待转换字符串    
///     
public static string GBToUnicode(string str)    

///     
/// 转换一个字符,输入如\"Π\"中的\"03a0\"    
///     
/// 待转换字符串    
///     
public static string ConvertSingle(string unicodeSingle)    

///     
/// unicode编码转换成GB2312汉字     
///     
/// 待转换字符串    
///     
public static string UnicodeToGB(string str)

2)辅助类的使用例子代码如下所示

private void btnUnicodeHelper_Click(object sender, EventArgs e)    
{    
    string str = \"\\u821e\\u7fbd\\u6e05\\u548c \\u5c71\\u7f8a\\u4e4b\\u89d2\";    
    string test = UnicodeHelper.UnicodeToString(str);    
    string result = test + \"\\r\\n\";    
    result += UnicodeHelper.StringToUnicode(test) + \"\\r\\n\";    

    MessageUtil.ShowTips(result);    
}

相关内容

热门资讯

Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
Apache Doris 2.... 亲爱的社区小伙伴们,我们很高兴地向大家宣布,Apache Doris 2.0.0 版本已于...
python清除字符串里非数字... 本文实例讲述了python清除字符串里非数字字符的方法。分享给大家供大家参考。具体如下: impor...