日期:2014-05-18 浏览次数:21253 次
    /// <summary>
    /// 读取指定格式XML文件(记录了TreeList控件被修改信息的xml),返回被修改对象集合
    /// </summary>
    /// <param name="xml">目标xml文件</param>
    /// <param name="type">封装数据的对象类型</param>
    /// <returns>被修改的对象集合</returns>
    public IList ReadXML(XmlDocument xml, Type type)
    {
        ArrayList modifiedObjList = new ArrayList();
        Object obj = Activator.CreateInstance(type);
        Type objType = obj.GetType();
        PropertyInfo info = null;
        info = objType.GetProperty(nodes.Name);
        //判断对象是否有该属性
        if (info != null)
        {
            //为对象属性赋值
            info.SetValue(obj, TypeTransaction(nodes.InnerText, info.PropertyType), null);
        }
        modifiedObjList.Add(obj);
        return modifiedObjList 
      }
  /// <summary>
    /// 动态执行装箱操作
    /// </summary>
    /// <param name="value">属性的值</param>
    /// <param name="valueType">属性的类型</param>
    /// <returns>装箱后的对象</returns>
 public object TypeTransaction(string value, Type valueType)
    {
        if (valueType == typeof(string) || valueType == typeof(String) )
        {
            return value;
        }
        object obj = new object();
        try
        {
            #region 如何优化
            if (string.IsNullOrEmpty(value))
            {
                if (valueType == typeof(int))
                {
                    obj = default(int);
                }
                else if (valueType == typeof(double) || valueType == typeof(Double))
                {
                    obj = default(double);
                }
                else if (valueType == typeof(float))
                { 
                    obj = default(float);
                }
                else if (valueType == typeof(long))
                { 
                    obj = default(long);
                }
                else if (valueType == typeof(DateTime))
                { 
                    obj = default(DateTime);
                }
            }
            #endregion 如何优化
            else
            {
                obj = valueType.GetMethod("Parse", new Type[] { typeof(string) }).Invoke(null, new object[] { value });
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        return obj;
    }
string value = "1234"; object i = Convert.ChangeType(d, valueType);
------解决方案--------------------
public static IList<T> FillList<T>(System.Data.IDataReader reader)
{
IList<T> lst= new List<T>();
while (reader.Read())
{
T RowInstance = Activator.CreateInstance<T>();
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
{
try
{
int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
if (reader.GetValue(Ordinal) != DBNull.Value)
{
Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
}
}
catch
{
break;
}
}
}
lst.Add(Row