• C# 对象克隆,DataTable转LIST


    public class ConvertHelper<T> where T : new()
        {
            private static string module = "ConvertHelper.cs";
    
            public static ObservableCollection<T> ConvertToList(List<T> listobject)
            {
                ObservableCollection<T> collection = null;
                try
                {
                    collection = new ObservableCollection<T>(listobject);
                }
                catch (Exception ex)
                {
                    ServiceLocator.Current.GetInstance<IWriteLog>().Log(LogConstant.LogType.Exception, module,
                       "Error occurs on ConvertToList modules: {0}.", ex.Message);
                }
    
                return collection;
            }
    
            public static ObservableCollection<T> ConvertToObservable(DataTable dt)
            {
                ObservableCollection<T> collection = null;
    
                // 定义集合
                List<T> ts = new List<T>();
    
                try
                {
                    // 获得此模型的类型
                    Type type = typeof(T);
    
                    // 定义一个临时变量
                    string tempName = string.Empty;
    
                    // 遍历DataTable中所有的数据行
                    foreach (DataRow dr in dt.Rows)
                    {
                        T t = new T();
    
                        // 获得此模型的公共属性
                        PropertyInfo[] propertys = t.GetType().GetProperties();
    
                        // 遍历该对象的所有属性
                        foreach (PropertyInfo pi in propertys)
                        {
                            // 将属性名称赋值给临时变量
                            tempName = pi.Name;
    
                            // 检查DataTable是否包含此列(列名==对象的属性名)  
                            if (dt.Columns.Contains(tempName))
                            {
                                // 判断此属性是否有Setter 该属性不可写,直接跳出
                                if (!pi.CanWrite) continue;
    
                                // 取值
                                object value = dr[tempName];
    
                                // 如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                    pi.SetValue(t, value.ToString(), null);
                            }
                        }
    
                        // 对象添加到泛型集合中
                        ts.Add(t);
                    }
                    collection = new ObservableCollection<T>(ts);
                }
                catch (Exception ex)
                {
                    ServiceLocator.Current.GetInstance<IWriteLog>().Log(LogConstant.LogType.Exception, module,
                      "Error occurs on ConvertToList modules: {0}.", ex.Message);
                }
    
                return collection;
            }
    
            /// 利用反射和泛型
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static List<T> ConvertToList(DataTable dt)
            {
                // 定义集合
                List<T> ts = new List<T>();
    
                try
                {
                    // 获得此模型的类型
                    Type type = typeof(T);
    
                    // 定义一个临时变量
                    string tempName = string.Empty;
    
                    // 遍历DataTable中所有的数据行
                    foreach (DataRow dr in dt.Rows)
                    {
                        T t = new T();
    
                        // 获得此模型的公共属性
                        PropertyInfo[] propertys = t.GetType().GetProperties();
    
                        // 遍历该对象的所有属性
                        foreach (PropertyInfo pi in propertys)
                        {
                            // 将属性名称赋值给临时变量
                            tempName = pi.Name;
    
                            // 检查DataTable是否包含此列(列名==对象的属性名)  
                            if (dt.Columns.Contains(tempName))
                            {
                                // 判断此属性是否有Setter 该属性不可写,直接跳出
                                if (!pi.CanWrite) continue;
    
                                // 取值
                                object value = dr[tempName];
    
                                // 如果非空,则赋给对象的属性
                                if (value != DBNull.Value)
                                    pi.SetValue(t, value.ToString(), null);
                            }
                        }
    
                        // 对象添加到泛型集合中
                        ts.Add(t);
                    }
                }
                catch (Exception ex)
                {
                    ServiceLocator.Current.GetInstance<IWriteLog>().Log(LogConstant.LogType.Exception, module,
                      "Error occurs on ConvertToList modules: {0}.", ex.Message);
                }
    
                return ts;
            }
        }

    对象克隆赋值

     /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                List<Test> list = new List<Test>();
                Test test = new Test();
               
                test.ID = "1";
                test.NAME = "xz";
                list.Add(test);
                Test test1=new Test ();
                CopyValue(list[0], test1);
    
                test1.NAME = "xznihoa";
                list.Add(test1);
            }
    
            public static void CopyValue(object origin, object target)
            {
                System.Reflection.PropertyInfo[] properties = (target.GetType()).GetProperties();
                System.Reflection.PropertyInfo[]   fields = (origin.GetType()).GetProperties();
                for (int i = 0; i < fields.Length; i++)
                {
                    for (int j = 0; j < properties.Length; j++)
                    {
                        if (fields[i].Name == properties[j].Name && properties[j].CanWrite)
                        {
                            properties[j].SetValue(target, fields[i].GetValue(origin,null), null);
                        }
                    }
                }
            }
    
        }
    
        public class Test
        {
            public string ID { get; set; }
    
            public string NAME { get; set; }
        }
    

      

  • 相关阅读:
    Hibernate延迟加载
    java.io.FileNotFoundException: antlr-2.7.7.jar (系统找不到指定的路径。)[待解决]
    Eclipse中复制项目重命名后重新发布,项目名在地址栏仍然是原来的项目名”的问题
    Tomcat服务器启动失败:Could not publish server configuration for Tomcat v8.0 Server at localhost. Multiple Contexts have a path of
    SSH整合:Unable to instantiate Action, employeeAction, defined for 'emp-list' in namespace '/'employeeAction
    ApplicationContext详解以及多个ApplicationContext.xml的相互引用
    Tomcat启动失败:Server Tomcat v8.0 Server at localhost was unable to start within 45 seconds
    三大框架你理解多少?
    通过命令行查询可用的包的版本号
    使用create-react-app命令创建一个项目, 运行npm run eject报错
  • 原文地址:https://www.cnblogs.com/HelloXZ/p/3799737.html
Copyright © 2020-2023  润新知