隐藏

在C#中Hashtable与object实体对象互转的方法

发布:2022/12/6 17:38:53作者:管理员 来源:本站 浏览次数:711

/// <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;

}


/// <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;
}