赞
踩
作为一个菜鸟,因该有颗不甘做菜鸟的心。这里介绍一个C#中比较高级点的技术,反射技术。曾经有人说过当你懂了反射技术,就告别了菜鸟。这里先介绍一个反射的有趣例子。接下几天后来个系列讲解,希望大家收看。
将dataTable中的数据映射到对象的字段和属性。也是现在好多软件做的关系-对象映射技术。这里新建一个控制台程序。
- <span style="font-size:18px;">classFoo
-
- {
-
- publicstring Username = "";
-
- publicint Level { get; set; }
-
- }</span>
- <span style="font-size:18px;">staticDataTable GetTable()
-
- {
-
- DataTable dt = newDataTable();
-
- dt.Columns.Add("Username");
-
- dt.Columns.Add("Level", typeof(int));
-
- dt.Rows.Add("John", 1);
-
- dt.Rows.Add("Cait", 2);
-
- return dt;
-
- }</span>
- <span style="font-size:18px;"> //一个实例绑定
-
- static T BindData<T>(DataTable dt)
-
- {
-
- DataRow dr = dt.Rows[0];
-
- // Get all columns'name
-
- List<string> columns = newList<string>();
-
- foreach (DataColumn dc in dt.Columns)
-
- {
-
- columns.Add(dc.ColumnName);
-
- }
- // Create object
-
- var ob = Activator.CreateInstance<T>();
- // Get all fields
-
- var fields = typeof(T).GetFields();
-
- foreach (var fieldInfo in fields)
-
- {
-
- if(columns.Contains(fieldInfo.Name))
-
- {
-
- //Fill the data into the field
-
- fieldInfo.SetValue(ob, dr[fieldInfo.Name]);
-
- }
-
- }
- // Get allproperties
-
- var properties = typeof(T).GetProperties();
-
- foreach (var propertyInfo in properties)
-
- {
-
- if(columns.Contains(propertyInfo.Name))
-
- {
-
- //Fill the data into the property
-
- propertyInfo.SetValue(ob, dr[propertyInfo.Name]);
-
- }
-
- }
- return ob;
-
- }</span>
- //实例列绑定
-
- staticList<T>BindDataList<T>(DataTable dt)
-
- {
-
- List<string> columns = newList<string>();
-
- foreach (DataColumn dc in dt.Columns)
-
- {
-
- columns.Add(dc.ColumnName);
-
- }
- var fields = typeof(T).GetFields();
-
- var properties = typeof(T).GetProperties()
- List<T> lst = newList<T>();
-
- foreach (DataRow dr in dt.Rows)
-
- {
-
- var ob = Activator.CreateInstance<T>();
-
- foreach (var fieldInfo in fields)
-
- {
-
- if(columns.Contains(fieldInfo.Name))
-
- {
-
- fieldInfo.SetValue(ob, dr[fieldInfo.Name]);
-
- }
-
- }
-
- foreach (var propertyInfo in properties)
-
- {
-
- if(columns.Contains(propertyInfo.Name))
-
- {
-
- propertyInfo.SetValue(ob, dr[propertyInfo.Name]);
-
- }
-
- }
- lst.Add(ob);
-
- }
-
- return lst;
-
- }
- <span style="font-size:18px;">staticvoid Main(string[] args)
-
- {
-
- DataTable dt = GetTable();
-
- Foo foo = BindData<Foo>(dt);
-
- Console.WriteLine("输出单个实体转化");
-
- Console.Write("名字:{0}, ",foo.Username);
-
- Console.Write("Level:{0}",foo.Level);
-
- Console.WriteLine();
-
- List<Foo> lstFoo =BindDataList<Foo>(dt);
-
- Console.WriteLine("输出实体集合转化");
-
- foreach (Foo obj in lstFoo)
-
- {
-
- Console.Write("名字:{0}, ", obj.Username);
-
- Console.Write("Level:{0}",obj.Level);
-
- Console.WriteLine();
-
- }
-
- Console.Read();
-
- }</span>
复杂的事情都是有很多简单是事情组成,一点一点早日摆脱菜鸟。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。