C# Hashtable与object实体对象互转
作者:C/S框架网  发布日期:2018-08-15 15:29:33
  C# Hashtable与object实体对象互转



C# Code:

/// <summary>
/// C# Hashtable转object实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T Hashtable2Object<T>(Hashtable source)
{
   T obj = Activator.CreateInstance<T>();
   object tv;
   
   PropertyInfo[] ps = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
   foreach (PropertyInfo p in ps)
   {
      if (source.ContainsKey(p.Name))
      {
         tv = source[p.Name];
         
         if (p.PropertyType.IsArray)//数组类型,单独处理
         {
            p.SetValue(obj, tv, null);
         }
         else
         {
            if (String.IsNullOrEmpty(tv.ToString()))//空值
            tv = p.PropertyType.IsValueType ? Activator.CreateInstance(p.PropertyType) : null;//值类型
            else
            tv = System.ComponentModel.TypeDescriptor.GetConverter(p.PropertyType).ConvertFromString(tv.ToString());//创建对象
            
            p.SetValue(obj, tv, null);
         }
         
      }
   }
   
   return obj;
}

//来源:C/S框架网(www.csframework.com) QQ:23404761




C# Code:


/// <summary>
/// C# 实体对象Object转HashTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public Hashtable Object2Hashtable(object obj)
{
   Hashtable hash = new Hashtable();
   
   PropertyInfo[] ps = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
   foreach (PropertyInfo p in ps)
   {
      hash.Add(p.Name, p.GetValue(obj));
   }
   
   return hash;
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



上一篇 下一篇