将一个对象相同的属性(不区分大小写)赋值给一个新对象 DataTable的一个简单的扩展

2023-05-13,,

将一个对象相同的属性(不区分大小写)赋值给一个新对象

 

 1 public static T Mapper<S, T>(S source)
 2         {
 3             T t = Activator.CreateInstance<T>();
 4             try
 5             {
 6                 var s_type = source.GetType();
 7                 var t_type = typeof(T);
 8                 foreach (PropertyInfo sp in s_type.GetProperties())
 9                 {
10                     foreach (PropertyInfo dp in t_type.GetProperties())
11                     {
12                         if (dp.Name.ToUpper() == sp.Name.ToUpper())
13                         {
14                             dp.SetValue(t, sp.GetValue(source, null), null);
15                         }
16                     }
17                 }
18             }
19             catch (Exception ex)
20             {
21                 throw ex;
22             }
23             return t;
24         }

DataTable的一个简单的扩展

 

我们在调试代码的时候经常遇到DataTable的数据类型错误,这个类可以帮助我们很快查看DataTable的结构信息.

 1 /// <summary>
 2 /// DataTable扩展类
 3 /// </summary>
 4 public static class DataTableExtensions
 5 {
 6     /// <summary>
 7     /// 显示DataTable的结构信息
 8     /// </summary>
 9     /// <param name="table">datatable</param>
10     public static void LoadDataTableStructure(this DataTable table)
11     {
12         if (table == null)
13         {
14             System.Diagnostics.Debug.WriteLine("datatable is null.");
15         }
16
17         StringBuilder structureInfo = new StringBuilder();
18         string colName = string.Empty;
19         string colType = string.Empty;
20
21         structureInfo.AppendLine("============================Begin=============================");
22         structureInfo.AppendLine("TableName: " + table.TableName);
23         structureInfo.AppendLine(string.Format("{0,-20}{1}", "ColumnName", "DataType"));
24
25         foreach (DataColumn col in table.Columns)
26         {
27             colName = col.ColumnName;
28             colType = col.DataType.ToString();
29             structureInfo.AppendLine(string.Format("{0,-20}{1}", colName, colType));
30         }
31
32         structureInfo.AppendLine("=============================End==============================");
33         System.Diagnostics.Debug.WriteLine(structureInfo.ToString());
34     }
35 }

将一个对象相同的属性(不区分大小写)赋值给一个新对象 DataTable的一个简单的扩展的相关教程结束。

《将一个对象相同的属性(不区分大小写)赋值给一个新对象 DataTable的一个简单的扩展.doc》

下载本文的Word格式文档,以方便收藏与打印。