Home > Article > Backend Development > Asp.net uses reflection to implement sample code analysis of assigning values to the model class
This article mainly introduces the method of asp.net using reflection to assign values to the model class. It analyzes the operating steps and related operating techniques of asp.net using reflection to assign values to the model class in the form of examples. Friends who need it can refer to
The example in this article describes the method of assigning values to the model class using reflection in asp.net. Share it with everyone for your reference, the details are as follows:
/// <summary> /// 给model类自动赋值 /// </summary> /// <param name="sqlstring">获取查询一个model实例的sql语句</param> /// <param name="obj">model实例对象</param> /// <returns></returns> public object selmodel(string sqlstring,object obj) { DataTable dtsell = lcommonbll.GetTable(sqlstring); int count = dtsell.Rows.Count; if (count == 0) { return null; } else { DataRow dr = dtsell.Rows[0]; #region 另一种方法 //foreach (DataColumn col in dr.Table.Columns) //{ // PropertyInfo pt = seller.GetType().GetProperty(col.ColumnName); // if (String.IsNullOrEmpty(dr[col.ColumnName].ToString())) // { // break; // } // else // { // pt.SetValue(seller, dtsell.Rows[0][0], null); // } //} #endregion foreach (System.Reflection.PropertyInfo pi in obj.GetType().GetProperties()) { if (pi.CanWrite) { try { if (dtsell.Rows[0][pi.Name]!=null) { pi.SetValue(obj, dtsell.Rows[0][pi.Name], null); } else { pi.SetValue(obj, null, null); } } catch { pi.SetValue(obj, null, null); } } } return obj; } }
.CS call
Seller seller = new Seller();//实体类 bind BIND = new bind();//绑定方法类 seller = (Seller)BIND.selmodel("select * from seller where SID=2", seller);//赋值
The above is the detailed content of Asp.net uses reflection to implement sample code analysis of assigning values to the model class. For more information, please follow other related articles on the PHP Chinese website!