using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Nirvana.Common
{
///
/// HashTable和object互转
///
public class HashTableHelper
{
///
/// Hashtable转object实体对象
///
///
///
///
public static T Hashtable2Object(Hashtable source)
{
T obj = Activator.CreateInstance();
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;
}
///
/// 实体对象Object转HashTable
///
///
///
///
public static 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;
}
}
}