国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#反射的應用

2019-11-17 02:53:54
字體:
來源:轉載
供稿:網友

C#反射的應用

項目框架中有一個很實用的方法,它用來獲取客戶端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");


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安远县| 石狮市| 华池县| 锡林郭勒盟| 南召县| 鸡泽县| 喀喇沁旗| 翼城县| 资中县| 民权县| 象州县| 尼玛县| 怀远县| 舞钢市| 库车县| 丹凤县| 县级市| 太和县| 齐齐哈尔市| 西宁市| 聊城市| 喀喇| 延边| 澜沧| 剑阁县| 萨迦县| 定襄县| 疏勒县| 聂荣县| 武穴市| 田林县| 洱源县| 德江县| 冕宁县| 钟山县| 汉中市| 潢川县| 潢川县| 武陟县| 大竹县| 津南区|