asp.net reflection reduces code writing

  • 2020-06-12 08:53:37
  • OfStack


public bool Add(Liuyan refmodel)
    {
        string sql = "insert into liuyan(name,phone,zhiwei,gongsi,addr,country,dianyou,content,adddate)values(@name,@phone,@zhiwei,@gongsi,@addr,@country,@dianyou,@content,@adddate)";
        OleDbParameter[] parameters ={
            new OleDbParameter("@name",OleDbType.VarChar),
            new OleDbParameter("@tel",OleDbType.VarChar),
            new OleDbParameter("@zhiwei",OleDbType.VarChar),
            new OleDbParameter("@gongsi",OleDbType.VarChar),
            new OleDbParameter("@addr",OleDbType.VarChar),
            new OleDbParameter("@country",OleDbType.VarChar),
            new OleDbParameter("@dianyou",OleDbType.VarChar),
            new OleDbParameter("@content",OleDbType.VarChar),
            new OleDbParameter("@adddate",OleDbType.VarChar)
        };
        parameters[0].Value=model.Xingming;
        parameters[1].Value=model.Tel;
        parameters[2].Value=model.Zhiwei;
        parameters[3].Value=model.Gongsi;
        parameters[4].Value=model.Addr;
        parameters[5].Value=model.Country;
        parameters[6].Value=model.Dianyou;
        parameters[7].Value=model.Content;
        parameters[8].Value=model.Adddate;
        return sqlHelper.executeCommand(sql, parameters);
    }
 

This article on reflection now says that the use of reflection in this code is just a whim of my coding process to save energy

   parameters[0].Value=model.Xingming;
        parameters[1].Value=model.Tel;
        parameters[2].Value=model.Zhiwei;
        parameters[3].Value=model.Gongsi;
        parameters[4].Value=model.Addr;
        parameters[5].Value=model.Country;
        parameters[6].Value=model.Dianyou;
        parameters[7].Value=model.Content;
        parameters[8].Value=model.Adddate;

The above code can use reflection to assign values when there are many properties in the class


    
// Use reflection to remember references using System.Reflection; The namespace 
     Type t = refmodel.GetType();
       for (int i = 0; i < t.GetProperties().Length; i++)
        {
            parameters[i].Value= t.GetProperties()[i].GetValue(refmodel, null);
        }


Reflection is used here to get all the properties of the class
The property is then traversed and the value of the traversal property is assigned to the parameter
Of course here is the method added without model.Id
So the for loop starts at 1
Then parameters[i]. i subtracted 1 parameters[ES23en-1].Value
So you don't have to go through the pain of copying and pasting one by one when you write to the data layer
How can a person be careful to share with others
Code generation tools can be used regardless


Related articles: