【C#公共帮助类】 Convert帮助类

大家知道,开发项目除了数据访问层很重要外,就是Common了,这里就提供了强大且实用的工具。

 

【C#公共帮助类】 Image帮助类

 

一、DataTable

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

namespace Common
{
    public partial class DataTable
    {
        /// <summary>
        /// 转换 DataTable 对象为 IList 对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <returns>数组对象</returns>
        public static T[] ToArray<T>(DataTable datas) where T : class, new()
        {
            List<T> list = ToList<T>(datas) as List<T>;
            return list.ToArray();
        }

        /// <summary>
        /// 转换IList对象为DataTable对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ToDataTable<T>(IList<T> datas)
        {
            return ToDataTable<T>(datas, null);
        }

        /// <summary>
        /// 转换IList对象为DataTable对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ToDataTable<T>(T[] datas)
        {
            return ToDataTable<T>(datas, null);
        }

        /// <summary>
        /// 转换IList对象为DataTable对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <param name="tableName">要创建的表名</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ToDataTable<T>(IList<T> datas, string tableName)
        {
            Type type = typeof(T);
            if (string.IsNullOrEmpty(tableName))
            {
                tableName = type.Name;
            }
            DataTable table = new DataTable(tableName);
            table.BeginLoadData();
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo info in properties)
            {
                string typeName = info.PropertyType.ToString();
                if (info.PropertyType.IsGenericType)
                {
                    typeName = info.PropertyType.GetGenericArguments()[0].ToString();
                }
                Type type2 = Type.GetType(typeName, false);
                if (type2 != null)
                {
                    table.Columns.Add(info.Name, type2);
                }
            }
            if ((datas != null) && (datas.Count > 0))
            {
                foreach (object obj2 in datas)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyInfo info2 in properties)
                    {
                        if ((Type.GetType(info2.PropertyType.ToString(), false) != null) && (info2.GetValue(obj2, null) != null))
                        {
                            row[info2.Name] = info2.GetValue(obj2, null);
                        }
                    }
                    table.Rows.Add(row);
                }
            }
            table.EndLoadData();
            table.AcceptChanges();
            return table;
        }

        public static DataTable ListToDataTable(object datas, string tableName)
        {
            Type type = ZGeneric.GetGenericType(datas);
            if (string.IsNullOrEmpty(tableName))
                tableName = type.Name;
            
            DataTable table = new DataTable(tableName);
            table.BeginLoadData();

            var properties = ZReflection.GetProperties(type);
            foreach (var p in properties)
            {
                Type colType = p.Value.PropertyType;
                string typeName = colType.ToString();
                if (colType.IsGenericType)
                    typeName = colType.GetGenericArguments()[0].ToString();
                
                Type newType = Type.GetType(typeName, false);
                if (newType != null)
                    table.Columns.Add(p.Value.Name, newType);
            }

            IEnumerator enumerator = ((dynamic)datas).GetEnumerator();
            while (enumerator.MoveNext())
            {
                DataRow row = table.NewRow();
                foreach (var p in properties)
                {
                    var value = ZGeneric.GetValue(enumerator.Current, p.Value.Name);
                    if ((Type.GetType(p.Value.PropertyType.ToString(), false) != null) && (value != null))
                        row[p.Value.Name] = value;
                }
                table.Rows.Add(row);
            }
            table.EndLoadData();
            table.AcceptChanges();
            return table;
        }

        /// <summary>
        /// 转换IList对象为DataTable对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <param name="tableName">要创建的表名</param>
        /// <returns>DataTable对象</returns>
        public static DataTable ToDataTable<T>(T[] datas, string tableName)
        {
            IList<T> list;
            if ((datas == null) || (datas.Length == 0))
            {
                list = new List<T>();
            }
            else
            {
                list = new List<T>(datas);
            }
            return ToDataTable<T>(list, tableName);
        }

        /// <summary>
        /// 转换 DataTable 对象为 IList 对象
        /// </summary>
        /// <param name="datas">数据集合</param>
        /// <returns>IList 对象</returns>
        public static IList<T> ToList<T>(DataTable datas) where T : class, new()
        {
            IList<T> list = new List<T>();
            if ((datas != null) && (datas.Rows.Count != 0))
            {
                PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (DataRow row in datas.Rows)
                {
                    T local = Activator.CreateInstance<T>();
                    foreach (DataColumn column in datas.Columns)
                    {
                        object obj2 = null;
                        if (row.RowState == DataRowState.Deleted)
                        {
                            obj2 = row[column, DataRowVersion.Original];
                        }
                        else
                        {
                            obj2 = row[column];
                        }
                        if (obj2 != DBNull.Value)
                        {
                            foreach (PropertyInfo info in properties)
                            {
                                if (column.ColumnName.Equals(info.Name, StringComparison.CurrentCultureIgnoreCase))
                                {
                                    info.SetValue(local, obj2, null);
                                }
                            }
                        }
                    }
                    list.Add(local);
                }
            }
            return list;
        }
    }
}

 

二、Enum

 public static T ToEnum<T>(object obj, T defaultEnum)
        {
            string str = To<string>(obj);

            if (Enum.IsDefined(typeof(T),str))
                return (T)Enum.Parse(typeof(T),str);

            int num;
            if (int.TryParse(str, out num))
            {
                if (Enum.IsDefined(typeof(T), num))
                    return (T)Enum.ToObject(typeof(T), num);
            }

            return defaultEnum;
        }

三、Generics

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

namespace Common
{
    public partial class Generics
    {
        /// <summary>
        /// 转换object为 T 值   
        /// </summary>
        /// <typeparam name="T">T 类型</typeparam>
        /// <param name="obj">要被转换的值</param>
        /// <returns>T 类型值</returns>
        public static T To<T>(object obj)
        {
            return To<T>(obj, default(T));
        }

        /// <summary>
        /// 转换object为 T 值   
        /// </summary>
        /// <typeparam name="T">T 类型</typeparam>
        /// <param name="obj">要被转换的值</param>
        /// <returns>T 类型值</returns>
        public static T To<T>(object obj,T defaultValue)
        {
            if (obj==null)
            {
                return defaultValue;
            }
            else if (obj is T)
            {
                return (T)obj;
            }
            else
            {
                try
                {
                    Type conversionType = typeof(T);
                    object obj2 = null;
                    if (conversionType.Equals(typeof(Guid)))
                        obj2 = new Guid(Convert.ToString(obj));
                    else
                        obj2 = Convert.ChangeType(obj, conversionType);
                    return (T)obj2;
                }
                catch (Exception)
                {
                    return defaultValue;
                }
            }
        }

        /// <summary>
        /// 填充客户端提交的值到 T 对象  如appinfo = AppConvert.To<Appinfo>(context.Request.Form);
        /// </summary>
        /// <typeparam name="T">T 类</typeparam>
        /// <param name="datas">客户端提交的值</param>
        /// <returns>T 对象</returns>
        public static T To<T>(NameValueCollection datas) where T : class, new()
        {
            Type type = typeof(T);
            string[] strArray = type.FullName.Split(new char[] { '.' });
            string str = strArray[strArray.Length - 1];
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            T local = Activator.CreateInstance<T>();
            foreach (string str2 in datas.AllKeys)
            {
                string str3 = datas[str2];
                if (!string.IsNullOrEmpty(str3))
                {
                    str3 = str3.TrimEnd(new char[0]);
                }
                foreach (PropertyInfo info in properties)
                {
                    string str4 = string.Format("{0}.{1}", str, info.Name);
                    if (str2.Equals(info.Name, StringComparison.CurrentCultureIgnoreCase) || str2.Equals(str4, StringComparison.CurrentCultureIgnoreCase))
                    {
                        string typeName = info.PropertyType.ToString();
                        if (info.PropertyType.IsGenericType)
                        {
                            typeName = info.PropertyType.GetGenericArguments()[0].ToString();
                        }
                        object nullInternal = GetNullInternal(info.PropertyType);
                        Type conversionType = Type.GetType(typeName, false);
                        if (!string.IsNullOrEmpty(str3))
                        {
                            nullInternal = Convert.ChangeType(str3, conversionType);
                        }
                        info.SetValue(local, nullInternal, null);
                    }
                }
            }
            return local;
        }

        #region 获取类型的默认值
        //另一种获取默认值的方法
        private static object GetDefaultValue(Type type)
        {
            object value = null;

            if (type.IsValueType)
                value = Activator.CreateInstance(type);
            else
                value = null;

            return value;
        }

        // 获取指定类型的默认值.引用类型(包含String)的默认值为null
        private static T DefaultValue<T>()
        {
            return default(T);
        }

        //获取默认值
        private static object GetNullInternal(Type type)
        {
            if (type.IsValueType)
            {
                if (type.IsEnum)
                {
                    return GetNullInternal(Enum.GetUnderlyingType(type));
                }
                if (type.IsPrimitive)
                {
                    if (type == typeof(int))
                    {
                        return 0;
                    }
                    if (type == typeof(double))
                    {
                        return 0.0;
                    }
                    if (type == typeof(short))
                    {
                        return (short)0;
                    }
                    if (type == typeof(sbyte))
                    {
                        return (sbyte)0;
                    }
                    if (type == typeof(long))
                    {
                        return 0L;
                    }
                    if (type == typeof(byte))
                    {
                        return (byte)0;
                    }
                    if (type == typeof(ushort))
                    {
                        return (ushort)0;
                    }
                    if (type == typeof(uint))
                    {
                        return 0;
                    }
                    if (type == typeof(ulong))
                    {
                        return (ulong)0L;
                    }
                    if (type == typeof(ulong))
                    {
                        return (ulong)0L;
                    }
                    if (type == typeof(float))
                    {
                        return 0f;
                    }
                    if (type == typeof(bool))
                    {
                        return false;
                    }
                    if (type == typeof(char))
                    {
                        return '\0';
                    }
                }
                else
                {
                    if (type == typeof(DateTime))
                    {
                        return DateTime.MinValue;
                    }
                    if (type == typeof(decimal))
                    {
                        return 0M;
                    }
                    if (type == typeof(Guid))
                    {
                        return Guid.Empty;
                    }
                    if (type == typeof(TimeSpan))
                    {
                        return new TimeSpan(0, 0, 0);
                    }
                }
            }
            return null;
        }
        #endregion
    }
}
View Code

四、String

     /// <summary>
        /// 转换为string类型 defult为string.Empty
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToString(object obj)
        {
             return To<string>(obj,string.Empty);
        }

五、TreeData

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

namespace Common
{
    public partial class TreeData
    {
        public static List<dynamic> ListToTreeData<T>(List<T> source, string ID, string PID) where T : class, new()
        {
            Action<List<dynamic>, T, dynamic> AddItem = (parent, item, Recursive) =>
            {
                var childrens = new List<dynamic>();
                var thisitem = ZGeneric.GetDictionaryValues(item);

                source.FindAll(o => ZGeneric.GetValue(item, ID).Equals(ZGeneric.GetValue(o, PID)))
                      .ForEach(subitem => { Recursive(childrens, subitem, Recursive); });

                thisitem.Add("children", childrens);
                parent.Add(thisitem);
            };

            var target = new List<dynamic>();
            source.FindAll(m => { return !source.Exists(n => ZGeneric.GetValue(n, ID).Equals(ZGeneric.GetValue(m, PID))); })
                  .ForEach(item => AddItem(target, item, AddItem));

            return target;
        }

        public static List<T> TreeDataToList<T>(List<dynamic> source)
        {
            Action<List<dynamic>, List<T>, dynamic> AddItem = (mysource, mytarget, Recursive) =>
            {
                foreach (var oldrow in mysource)
                {
                    var newrow = ZGeneric.CreateNew<T>();
                    var dictionary = (IDictionary<string, object>)ZGeneric.GetDictionaryValues(oldrow);

                    var childern = dictionary["childern"] as List<dynamic>;
                    if (childern.Count > 0) Recursive(mysource, mytarget, Recursive);

                    foreach (var property in dictionary)
                        if (property.Key != "children")
                            ZGeneric.SetValue(newrow, property.Key, property.Value);

                    mytarget.Add(newrow);
                }
            };

            var target = new List<T>();
            AddItem(source, target, AddItem);

            return target;
        }
    }
}

 

转载于:https://www.cnblogs.com/eadily-dream/p/5525880.html

WHC.OrderWater.Commons 伍华聪 公共源码 帮助文档 本资料共包含以下附件: WHC.OrderWater.Commons.rar 公共文档.docx ----------------------------------------------------------- ----------Database-------------- 1.DataTable帮助(DataTableHelper.cs) 2.Access数据库文件操作辅助(JetAccessUtil.cs) 5.查询条件组合辅助(SearchCondition.cs) 6.查询信息实体(Search Info.cs) 8.Sql命令操作函数(可用于安装程序的时候数据库脚本执行)(SqlScriptHelper.cs) ----------Device-------------- 声音播放辅助(AudioHelper.cs) 摄像头操作辅助,包括开启、关闭、抓图、设置等功能(Camera.cs) 提供用于操作【剪切板】的方法(ClipboardHelper.cs) 获取电脑信息(Computer.cs) 提供用户硬件唯一信息的辅助(FingerprintHelper.cs) 读取指定盘符的硬盘序列号(HardwareInfoHelper.cs) 提供访问键盘当前状态的属性(KeyboardHelper.cs) 全局键盘钩子。这可以用来在全球范围内捕捉键盘输入。(KeyboardHook.cs) 模拟鼠标点击(MouseHelper.cs) 全局鼠标钩子。这可以用来在全球范围内捕获鼠标输入。(MouseHook.cs) MP3文件播放操作辅助(MP3Helper.cs) 关联文件(ExtensionAttachUtil.cs) 注册文件关联的辅助(FileAssociationsHelper.cs) 打开、保存文件对话框操作辅助(FileDialogHelper.cs) 常用的文件操作辅助FileUtil(FileUtil.cs) INI文件操作辅助(INIFileUtil.cs) 独立存储操作辅助(IsolatedStorageHelper.cs) 序列号操作辅助(Serializer.cs) 获取一个对象,它提供用于访问经常引用的目录的属性。(SpecialDirectories.cs) 简单的Word操作对象(WordCombineUtil.cs) 这个提供了一些实用的方法来转换XML和对象。(XmlConvertor.cs) XML操作(XmlHelper.cs) ----------Format-------------- 参数验证的通用验证程序。(ArgumentValidation.cs) 这个提供了实用方法的字节数组和图像之间的转换。(ByteImageConvertor.cs) byte字节数组操作辅助(BytesTools.cs) 处理数据型转换,数制转换、编码转换相关的(ConvertHelper.cs) CRC校验辅助(CRCUtils.cs) 枚举操作公共(EnumHelper.cs) 身份证操作辅助(IDCardHelper.cs) 检测字符编码的(IdentifyEncoding.cs) RGB颜色操作辅助(MyColors.cs) 日期操作(MyDateTime.cs) 转换人民币大小金额辅助(RMBUtil.cs) 常用的字符串常量(StringConstants.cs) 简要说明TextHelper。(StringUtil.cs) 获取中文字首字拼写,随机发生器,按指定概率随机执行操作(Util.cs) 各种输入格式验证辅助(ValidateUtil.cs) ----------Network-------------- Cookie操作辅助(CookieManger.cs) FTP操作辅助(FTPHelper.cs) HTML操作(HttpHelper.cs) 网页抓取帮助(HttpWebRequestHelper.cs) Net(NetworkUtil.cs) IE代理设置辅助(ProxyHelper.cs) ----------Winform-------------- 跨线程的控件安全访问方式(CallCtrlWithThreadSafety.cs) CheckBoxList(CheckBoxListUtil.cs) 窗口管理(ChildWinManagement.cs) ChildWinManagement
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值