C#反射的應用

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   使用   ar   strong   for   

     項目架構中有一個很實用的方法,它用來擷取用戶端post的資料,並自動賦值到對象各屬性,這樣後台少寫了很多代碼。但是對於有主表、子表的表單,架構中沒有提供自動給子表對象各屬性賦值的方法,每次都要寫很多代碼,各種判斷,各種迴圈,一個屬性一個屬性地賦值,很不方便,所以我就嘗試寫了一個自動賦值的方法,用到了C#反射的知識,當然,還不夠完善,方法代碼如下:

public List<T> GetList<T>(MvcContext ctx, string label) where T : new(){    List<T> tList = new List<T>();    int count = 0;    // 擷取資料條數    PropertyInfo[] pInfoList = (typeof(T)).GetProperties();    foreach (PropertyInfo pInfo in pInfoList)    {        string values = ctx.Post(label + "." + pInfo.Name);        if (!strUtil.IsNullOrEmpty(values))        {            count = values.Split(‘,‘).Length;            break;        }    }    // 給每條資料賦值    for (int i = 0; i < count; i++)    {        T t = new T();        PropertyInfo[] propertyInfoList = (typeof(T)).GetProperties();        foreach (PropertyInfo propertyInfo in propertyInfoList) // 遍曆實體的屬性,以給實體的屬性賦值        {            string values = ctx.Post(label + "." + propertyInfo.Name);            if (!strUtil.IsNullOrEmpty(values))            {                string[] valueArray = values.Split(‘,‘);
if(!strUtil.IsNullOrEmpty(valueArray[i]))
{ #region 判斷實體的屬性的類型並賦值 if (propertyInfo.PropertyType == typeof(int)) { int val = int.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(decimal)) { decimal val = decimal.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(string)) { string val = valueArray[i]; propertyInfo.SetValue(t, val, null); } if (propertyInfo.PropertyType == typeof(DateTime)) { DateTime val = DateTime.Parse(valueArray[i]); propertyInfo.SetValue(t, val, null); } #endregion
}
} } tList.Add(t); } return tList;}

 方法的使用如下:

List<IMP_PurchasePayRealDtl> purchasePayRealDtlList = GetList<IMP_PurchasePayRealDtl>(ctx, "purchasePayRealDtl");

 

C#反射的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.