使用反射实例化对象(代码)

注:目前还不能完全理解“反射”,故只记录代码,待思维成熟后补全理解

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using System.Data;
  7 
  8 using System.Reflection;
  9 namespace LoadCode
 10 {
 11     /// <summary>
 12     /// 反射实例化对象
 13     /// </summary>
 14     public class CreateObject
 15     {
 16         public bool Success { get; set; } = true;
 17         public string ErrorMessage { get; set; } = string.Empty;
 18 
 19         private T Invoke<T>(Func<T> func) where T : class, new()
 20         {
 21             T obj = default(T);
 22             try
 23             {
 24                 Success = true;
 25                 ErrorMessage = string.Empty;
 26                 obj = func.Invoke();
 27             }
 28             catch (Exception ex)
 29             {
 30                 Success = false;
 31                 ErrorMessage = string.Format("对象实例化异常:{0}->{1}", ex.Message, ex.StackTrace);
 32             }
 33             return obj;
 34         }
 35 
 36         private List<T> Invoke<T>(Func<List<T>> func) where T : class, new()
 37         {
 38             List<T> objList = new List<T>();
 39             try
 40             {
 41                 Success = true;
 42                 ErrorMessage = string.Empty;
 43                 objList = func.Invoke();
 44             }
 45             catch (Exception ex)
 46             {
 47                 Success = false;
 48                 ErrorMessage = string.Format("对象实例化异常:{0}->{1}", ex.Message, ex.StackTrace);
 49             }
 50             return objList;
 51         }
 52 
 53         /// <summary>
 54         /// 使用DataSet实例化对象
 55         /// </summary>
 56         /// <typeparam name="T"></typeparam>
 57         /// <param name="ds"></param>
 58         /// <returns></returns>
 59         public T CreateObjectByDataSet<T>(DataSet ds) where T : class, new()
 60         {
 61             return Invoke(() =>
 62             {
 63                 T obj = default(T);
 64                 Type _type = typeof(T);
 65                 if (ds.Equals(null))
 66                 {
 67                     return obj;
 68                 }
 69                 PropertyInfo[] propertys = _type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
 70                 ConstructorInfo info = _type.GetConstructor(new Type[] { });
 71                 obj = (T)info.Invoke(new object[] { });
 72                 for (int i = 0; i < propertys.Length; i++)
 73                 {
 74                     PropertyInfo ProInfo = propertys[i];
 75                     if (ds.Tables[0].Columns.IndexOf(ProInfo.Name) != -1 && !obj.Equals(null))
 76                     {
 77                         ProInfo.SetValue(obj, ds.Tables[0].Rows[0][ProInfo.Name]);
 78                     }
 79                 }
 80                 return obj;
 81             });
 82         }
 83 
 84         /// <summary>
 85         /// 使用DataSet实例化对象列表
 86         /// </summary>
 87         /// <typeparam name="T"></typeparam>
 88         /// <param name="ds"></param>
 89         /// <returns></returns>
 90         public List<T> CreateObjectsByDataSet<T>(DataSet ds) where T : class, new()
 91         {
 92             return Invoke(() =>
 93             {
 94                 List<T> objList = new List<T>();
 95                 Type _type = typeof(T);
 96                 if (ds.Equals(null))
 97                 {
 98                     return objList;
 99                 }
100                 PropertyInfo[] ProInfos = _type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
101                 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
102                 {
103                     ConstructorInfo ConstInfo = _type.GetConstructor(new Type[] { });
104                     T obj = (T)ConstInfo.Invoke(new object[] { });
105                     for (int j = 0; j < ProInfos.Length; j++)
106                     {
107                         PropertyInfo ProInfo = ProInfos[j];
108                         if (ds.Tables[0].Columns.IndexOf(ProInfo.Name) != -1 && !obj.Equals(null))
109                         {
110                             ProInfo.SetValue(obj, ds.Tables[0].Rows[i][ProInfo.Name]);
111                         }
112                     }
113                     objList.Add(obj);
114                 }
115                 return objList;
116             });
117         }
118 
119 
120         /// <summary>
121         /// 使用DataSet根据对象构造函数实例化
122         /// Column数量对应构造函数参数数量
123         /// </summary>
124         /// <typeparam name="T"></typeparam>
125         /// <param name="ds"></param>
126         /// <returns></returns>
127         public T CreateObjectByConstructor<T>(DataSet ds) where T : class, new()
128         {
129             return Invoke(() =>
130               {
131                   T obj = default(T);
132                   if (ds == null || ds.Tables.Count <= 0)
133                   {
134                       return obj;
135                   }
136                   int cLenght = ds.Tables[0].Columns.Count;
137                   Type _type = typeof(T);
138                   Type[] types = new Type[cLenght];
139                   object[] objects = new object[cLenght];
140                   for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
141                   {
142                       types[i] = ds.Tables[0].Rows[0][i].GetType();
143                       objects[i] = ds.Tables[0].Rows[0][i];
144                   }
145                   ConstructorInfo ConstInfo = _type.GetConstructor(types);
146                   obj = (T)ConstInfo.Invoke(objects);
147                   return obj;
148               });
149         }
150 
151         /// <summary>
152         /// 使用DataSet根据对象构造函数实例化
153         /// Column数量对应构造函数参数数量
154         /// </summary>
155         /// <typeparam name="T"></typeparam>
156         /// <param name="arges"></param>
157         /// <returns></returns>
158         public List<T> CreateObjectsByConstructor<T>(DataSet arges) where T : class, new()
159         {
160             return Invoke(() =>
161             {
162                 List<T> list = new List<T>();
163                 Type t = typeof(T); //获取类型?
164                 if (arges.Equals(null))  //几列代表几个字段
165                 {
166                     return list;
167                 }
168                 int cLenght = arges.Tables[0].Columns.Count, rLenght = arges.Tables[0].Rows.Count;
169                 Type[] types = new Type[cLenght]; //反射对象的类型集合
170                 object[] param = new object[cLenght]; //反射对象的数据集合
171                 for (int i = 0; i < rLenght; i++)
172                 {
173                     for (int j = 0; j < cLenght; j++)
174                     {
175                         types[j] = arges.Tables[0].Rows[i][j].GetType();
176                         param[j] = arges.Tables[0].Rows[i][j];
177                     }
178                     ConstructorInfo info = t.GetConstructor(types);
179                     if (info != null)
180                     {
181                         list.Add((T)info.Invoke(param));
182                     }
183                     else
184                     {
185                         list.Add((T)Activator.CreateInstance(t, null));
186                     }
187                 }
188                 return list;
189             });
190         }
191 
192 
193         /// <summary>
194         /// 使用object[]实例化对象
195         /// </summary>
196         /// <typeparam name="T"></typeparam>
197         /// <param name="arges"></param>
198         /// <returns></returns>
199         public T CreateObjectsByParams<T>(params object[] arges) where T : class, new()
200         {
201             return Invoke(() =>
202             {
203                 T obj = default(T);
204                 Type t = typeof(T); //获取类型?
205                 if (arges.Equals(null))
206                 {
207                     return obj;
208                 }
209                 int lenght = arges.Length;
210                 Type[] types = new Type[lenght]; //类型集合?
211                 object[] param = new object[lenght]; //数据集合? 对象集合?
212                 for (int i = 0; i < lenght; i++)
213                 {
214                     types[i] = arges[i].GetType(); //添加类型?
215                     param[i] = arges[i]; //添加对象?上面为获取类型,这里为数据?数据的格式是什么?失去了类型数据会以什么样的形式表现?
216                 }
217                 ConstructorInfo info = t.GetConstructor(types); //获取类型集合里面所有的类型?
218                 if (info != null)
219                 {
220                     obj = (T)info.Invoke(param);
221                 }
222                 else
223                 {
224                     obj = (T)Activator.CreateInstance(t, null);
225                 }
226                 return obj;
227             });
228         }
229     }
230 }
View Code
原文地址:https://www.cnblogs.com/Z-onee/p/8136921.html