2017-02-20 25 views
0

如何動態地在C#創建類和List,爲前:如果我們通過數據設置方法應該返回列表格式的數據如何動態地在C#創建類和List

,但在傳統的模型每次我需要創建類和方法,所以任何有想法的人都可以分享它。

這是我的傳統方法代碼: -

[WebMethod] 
    public static List<ICF> ge_Grid_data(string paramstr, string procname) 
    { 
     #region 
     List<ICF> lst = new List<ICF>(); 
     try 
     { 
      string[] parameters = paramstr.Split('~'); 
      string err = string.Empty; 
      int len = parameters.Length; 
      SqlParameter[] sqlParam = new SqlParameter[len]; 
      for (int i = 0; i < len; i++) 
      { 
       string[] paramWithValue = parameters[i].Split('$'); 
       string param = paramWithValue[0].ToString(); 
       string value = paramWithValue[1].ToString(); 
       sqlParam[i] = new SqlParameter { ParameterName = param, Value = value }; 
      } 

      DataSet ds = new clsiCMSBLBase().GetListData(ref err, sqlParam, procname); 
      DataTable dt = ds.Tables[0]; 
      foreach (DataRow dr in dt.Rows) 
      { 
       ICF obj = new ICF(); 
       obj.Flag = Convert.ToInt32(dr["Flag"]); 
       obj.ClaimID = dr["ClaimID"].ToString(); 
       obj.RyotNumber = dr["RyotNumber"].ToString(); 
       obj.SeasonCode = dr["SeasonCode"].ToString(); 
       obj.PlotNumber = dr["PlotNumber"].ToString(); 
       obj.RyotNumber = dr["RyotNumber"].ToString(); 
       obj.RyotName = dr["RyotName"].ToString(); 
       obj.ClaimDate = dr["ClaimDate"].ToString(); 
       obj.ClaimFormNo = dr["ClaimFormNo"].ToString(); 
       obj.ClaimArea = dr["ClaimArea"].ToString(); 
       obj.ClaimAmount = dr["ClaimAmount"].ToString(); 
       obj.ClaimReason = dr["ClaimReason"].ToString(); 
       obj.SurveyorID = dr["SurveyorID"].ToString(); 
       obj.SurveyorDate = dr["SurveyorDate"].ToString(); 
       obj.InsuranceAmount = dr["InsuranceAmount"].ToString(); 

       lst.Add(obj); 
      } 
     } 
     catch (Exception ex) 
     { 
     } 

     return lst; 
     #endregion 
    } 

這裏是ICF類: -

public class ICF 
    { 
     #region 
     public int Flag { get; set; } 
     public string ClaimID { get; set; } 
     public string SeasonCode { get; set; } 
     public string PlotNumber { get; set; } 
     public string RyotNumber { get; set; } 
     public string RyotName { get; set; } 
     public string ClaimDate { get; set; } 
     public string ClaimFormNo { get; set; } 
     public string ClaimArea { get; set; } 
     public string ClaimAmount { get; set; } 
     public string ClaimReason { get; set; } 
     public string SurveyorID { get; set; } 
     public string SurveyorDate { get; set; } 
     public string InsuranceAmount { get; set; } 
     #endregion 
    } 

我的意料:

public static class Extensions 
{ 
    /// <summary> 
    /// Converts datatable to list<T> dynamically 
    /// </summary> 
    /// <typeparam name="T">Class name</typeparam> 
    /// <param name="dataTable">data table to convert</param> 
    /// <returns>List<T></returns> 
    public static List<T> ToList<T>(this DataTable dataTable) where T : new() 
    { 
     var dataList = new List<T>(); 

     //Define what attributes to be read from the class 
     const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; 

     //Read Attribute Names and Types 
     var objFieldNames = typeof(T).GetProperties(flags).Cast<PropertyInfo>(). 
      Select(item => new 
      { 
       Name = item.Name, 
       Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType 
      }).ToList(); 

     //Read Datatable column names and types 
     var dtlFieldNames = dataTable.Columns.Cast<DataColumn>(). 
      Select(item => new { 
       Name = item.ColumnName, 
       Type=item.DataType 
      }).ToList(); 

     foreach (DataRow dataRow in dataTable.AsEnumerable().ToList()) 
     { 
      var classObj = new T(); 

      foreach (var dtField in dtlFieldNames) 
      { 
       PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name); 

       var field = objFieldNames.Find(x => x.Name == dtField.Name); 

       if (field != null) 
       { 

        if (propertyInfos.PropertyType == typeof(DateTime)) 
        { 
         propertyInfos.SetValue 
         (classObj, convertToDateTime(dataRow[dtField.Name]), null); 
        } 
        else if (propertyInfos.PropertyType == typeof(int)) 
        { 
         propertyInfos.SetValue 
         (classObj, ConvertToInt(dataRow[dtField.Name]), null); 
        } 
        else if (propertyInfos.PropertyType == typeof(long)) 
        { 
         propertyInfos.SetValue 
         (classObj, ConvertToLong(dataRow[dtField.Name]), null); 
        } 
        else if (propertyInfos.PropertyType == typeof(decimal)) 
        { 
         propertyInfos.SetValue 
         (classObj, ConvertToDecimal(dataRow[dtField.Name]), null); 
        } 
        else if (propertyInfos.PropertyType == typeof(String)) 
        { 
         if (dataRow[dtField.Name].GetType() == typeof(DateTime)) 
         { 
          propertyInfos.SetValue 
          (classObj, ConvertToDateString(dataRow[dtField.Name]), null); 
         } 
         else 
         { 
          propertyInfos.SetValue 
          (classObj, ConvertToString(dataRow[dtField.Name]), null); 
         } 
        } 
       }     
      } 
      dataList.Add(classObj); 
     } 
     return dataList; 
    } 

    private static string ConvertToDateString(object date) 
    { 
     if (date == null) 
      return string.Empty; 

     return SpecialDateTime.ConvertDate(Convert.ToDateTime(date)); 
    } 

    private static string ConvertToString(object value) 
    { 
     return Convert.ToString(HelperFunctions.ReturnEmptyIfNull(value)); 
    } 

    private static int ConvertToInt(object value) 
    { 
     return Convert.ToInt32(HelperFunctions.ReturnZeroIfNull(value)); 
    } 

    private static long ConvertToLong(object value) 
    { 
     return Convert.ToInt64(HelperFunctions.ReturnZeroIfNull(value)); 
    } 

    private static decimal ConvertToDecimal(object value) 
    { 
     return Convert.ToDecimal(HelperFunctions.ReturnZeroIfNull(value)); 
    } 

    private static DateTime convertToDateTime(object date) 
    { 
     return Convert.ToDateTime(HelperFunctions.ReturnDateTimeMinIfNull(date)); 
    } 
} 

最後,我需要調用它像這樣:

List<MyClass> list = dt.ToList<MyClass> 

但是這個代碼不工作

+0

我不太清楚你問什麼,但你說的是自動映射?或者隨意輸入任意數據,您希望自動生成相應的cs類並使其成爲您解決方案的一部分?請問爲什麼要達到這個目的呢? –

+2

先解釋你的用例。看起來很奇怪,你想將一個通用模型映射到一個在運行中生成的強類型模型。 –

+0

是自動映射,因爲每次我需要創建如此多的List方法返回List Data到HTML頁面,所以如果我有共同的List方法意味着可以再次減少開發 – ethiraj

回答

0

儘管這不是很清楚你想要達到的目標,你可以請使用dynamic關鍵字和System.Dynamic.ExpandoObject並使用.Net> = 4來完成您所描述的內容。

+0

只是我手動推動數據一個手動好,但我需要做的一切自動化方式 – ethiraj

+0

只是查看上面提到的代碼數據集返回從數據庫並推到FOR-EACH循環然後我打電話給ICF類這裏只是我要求動態類(ICF),然後我需要在每次訪問不同的訪問時推送這種類型的對象obj.ClaimAmount = dr [「ClaimAmount」]。ToString();並返回列表 – ethiraj

+0

嗯 - 你可以序列化你的'DataTable'到JSON(http://stackoverflow.com/questions/2979922/how-to-convert-datatable-to-json-string-using-json-net)和反序列化動態(http://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net)。如果你絕對需要,那就是... – JeffRSon

0

在類中創建一個方法ICF

public class ICF 
    { 
     public static List<ICF> icfList = new List<ICF>(); 

     #region 
     public int Flag { get; set; } 
     public string ClaimID { get; set; } 
     public string SeasonCode { get; set; } 
     public string PlotNumber { get; set; } 
     public string RyotNumber { get; set; } 
     public string RyotName { get; set; } 
     public string ClaimDate { get; set; } 
     public string ClaimFormNo { get; set; } 
     public string ClaimArea { get; set; } 
     public string ClaimAmount { get; set; } 
     public string ClaimReason { get; set; } 
     public string SurveyorID { get; set; } 
     public string SurveyorDate { get; set; } 
     public string InsuranceAmount { get; set; } 
     #endregion 


     public static void AddRow(DataRow dr) 
     { 
       ICF obj = new ICF(); 
       obj.Flag = Convert.ToInt32(dr["Flag"]); 
       obj.ClaimID = dr["ClaimID"].ToString(); 
       obj.RyotNumber = dr["RyotNumber"].ToString(); 
       obj.SeasonCode = dr["SeasonCode"].ToString(); 
       obj.PlotNumber = dr["PlotNumber"].ToString(); 
       obj.RyotNumber = dr["RyotNumber"].ToString(); 
       obj.RyotName = dr["RyotName"].ToString(); 
       obj.ClaimDate = dr["ClaimDate"].ToString(); 
       obj.ClaimFormNo = dr["ClaimFormNo"].ToString(); 
       obj.ClaimArea = dr["ClaimArea"].ToString(); 
       obj.ClaimAmount = dr["ClaimAmount"].ToString(); 
       obj.ClaimReason = dr["ClaimReason"].ToString(); 
       obj.SurveyorID = dr["SurveyorID"].ToString(); 
       obj.SurveyorDate = dr["SurveyorDate"].ToString(); 
       obj.InsuranceAmount = dr["InsuranceAmount"].ToString(); 

       icfList.Add(obj); 
     } 
    } 
+0

那應該是全自動重用模式,所以不應該添加手動的代碼行或類或類對象 – ethiraj

0

**

我得到了答案這裏是序列化數據,並輕鬆地在HTML頁面 訪問使用jQuery的Ajax方法,這是再像普通方法 只是通過SP名稱,參數,表格順序(0表或第一表 無論您的願望),此模型可以用於填充數據控件或jqx部件網格綁定..等

**

[WebMethod] 
public static String GetRowData_Tables(string procedureName, string paramstr, int table) 
{ 
    string[] parameters = paramstr.Split('~'); 
    string err = string.Empty; 
    int len = parameters.Length; 
    SqlParameter[] sqlParam = new SqlParameter[len]; 
    for (int i = 0; i < len; i++) 
    { 
     string[] paramWithValue = parameters[i].Split('$'); 
     string param = paramWithValue[0].ToString(); 
     string value = paramWithValue[1].ToString(); 
     sqlParam[i] = new SqlParameter { ParameterName = param, Value = value }; 
    } 

    try 
    { 
     DataSet ds = new clsiCMSBLBase().GetListData(ref err, sqlParam, procedureName); 
     String JSONString = String.Empty; 

     //JSONString = Newtonsoft.Json.JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented); 

     if (ds.Tables[table].Rows.Count > 0) 
     { 
      DataTable dt = ds.Tables[table]; 
      JSONString = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Newtonsoft.Json.Formatting.Indented); 
     } 

     return JSONString; 
    } 
    catch (Exception) 
    { 
     return "Error"; 
    } 
}