This article describes the C# implementation method that uses reflection to simplify assigning values to class fields. Share it for your reference. The specific analysis is as follows:
Explanation: The main idea of this example is to establish a class and database query statement that is consistent.
Then, using reflection, directly use the data field name to piece together and assign values to the fields of the class object.
1. Class definition
namespace CCB_Donet.ClassFolder { public class FieldRuleInfo { public string gStrFNo; public string gStrFName; public string gStrFLock; public string gStrFCaption; public string gStrFType; public string gStrFMust; public string gStrFMin; public string gStrFMax; public string gStrFDefault; public string gStrFDate; public string gStrFDB; public string gStrFAllow; public string gStrFDisallow; public string gStrFSB; public string gStrFBig; public string gStrFSmall; public string gStrFInputMethod; public string gStrFCHK; public string gStrFRelation; public string gStrFDesc; public string gStrFSecond; public string gStrFQC; public string gStrFException; public string gStrFASupp; public string gStrFYQH; public string gStrFPos; public string gStrFStar; public string gStrFSave; public string gStrFAddress; public string gStrFLblColor; public string gStrFIsCheckList; } } #region Loading field rules private bool m_GetRule() { string strSQL = ""; DataTable dtGet = null; #if(DEBUG) try { #endif if ( == 95) { strSQL = "select ,,,,," + ",,,,,\r\n" + ",,,,,,," + ",,,,\r\n" + ",,,,,,,"+ ",, from P_Field_Rule95 A \r\n" + "INNER JOIN P_Field_Initial B ON = \r\n" + "where =1 AND ='1' AND " + "(B.FRegion95=1 OR B.FRegion95=-1) ORDER BY "; } else { strSQL = "select ,,,,,"+ ",,,,,\r\n" + ",,,,,,"+ ",,,,,\r\n" + ",,,,,,"+ ",,, "+ "from P_Field_Rule A \r\n" + "INNER JOIN P_Field_Initial B ON = \r\n" + "where =" + () + " AND ='1' AND (=" + () + " OR =-1) ORDER BY "; } dtGet = (strSQL); if ( <= 0) { ("There is no data in the field rule table, please contact the software engineer immediately!", ); return false; } //Get class information and prepare for the following reflection call Type oType = ("CCB_Donet."); // Generate an array of class objects, which is consistent with the database records. mMainFieldRule = new FieldRuleInfo[]; for (int i = 0; i < ; i++) { // Here we use reflection dynamically to assign data to the FieldRuleInfo field mMainFieldRule[i] = new FieldRuleInfo(); for (int j = 0; j < ; j++) { // Here we directly get the field name of the class, and then assign the value of the corresponding field in the database to it FieldInfo fieldInfo = ("gStr" + [j].ColumnName, | | | ); (mMainFieldRule[i], [i][j].ToString()); } } return true; #if(DEBUG) } catch (Exception ex) { return false; ("frmDE-m_GetRule", ); } finally { dtGet = null; } #endif } #endregion
I hope this article will be helpful to everyone's C# programming.