如何在C#中动态创建类和List

时间:2017-02-20 10:42:05

标签: c#

如何在C#中动态创建类和List,例如:如果我们将数据集传递给应返回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>

但此代码无效

3 个答案:

答案 0 :(得分:0)

虽然您不太清楚自己想要实现的目标,但您可以使用dynamic关键字和System.Dynamic.ExpandoObject与.Net&gt; = 4来完成您所描述的内容

答案 1 :(得分: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);
        }
    }

答案 2 :(得分:0)

**

  

我得到了答案这是序列化数据,易于在HTML页面中访问   使用Jquery Ajax方法,这是可重用的代码,就像常用方法一样   只传递SP名称,参数,表顺序(第0表或第1表   无论您的愿望如何),此模型可用于填充数据到控件或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";
    }
}