C# 如何在C中动态创建类和列表#
如何在C#中动态创建类和列表,例如:如果我们将数据集传递给应该返回列表格式数据的方法 但在传统模型上,每次我都需要创建类和方法,所以任何有想法的人都可以分享 以下是我的常规方法代码:- 我的期望:C# 如何在C中动态创建类和列表#,c#,C#,如何在C#中动态创建类和列表,例如:如果我们将数据集传递给应该返回列表格式数据的方法 但在传统模型上,每次我都需要创建类和方法,所以任何有想法的人都可以分享 以下是我的常规方法代码:- 我的期望: 公共静态类扩展 { /// ///将数据表动态转换为列表 /// ///类名 ///要转换的数据表 ///名单 公共静态列表ToList(此数据表),其中T:new() { var dataList=新列表(); //定义要从类中读取的属性 const BindingFlags flags=Bin
公共静态类扩展
{
///
///将数据表动态转换为列表
///
///类名
///要转换的数据表
///名单
公共静态列表ToList(此数据表),其中T:new()
{
var dataList=新列表();
//定义要从类中读取的属性
const BindingFlags flags=BindingFlags.Public | BindingFlags.Instance;
//读取属性名称和类型
var objFieldNames=typeof(T).GetProperties(flags).Cast()。
选择(项目=>新建)
{
名称=项。名称,
Type=Nullable.GetUnderlineType(item.PropertyType)??item.PropertyType
}).ToList();
//读取数据表列名和类型
var dtlFieldNames=dataTable.Columns.Cast()。
选择(项=>new{
Name=item.ColumnName,
Type=item.DataType
}).ToList();
foreach(dataTable.AsEnumerable().ToList()中的DataRow DataRow)
{
var classObj=新的T();
foreach(dtlFieldNames中的var dtField)
{
PropertyInfo propertyInfos=classObj.GetType().GetProperty(dtField.Name);
var field=objFieldNames.Find(x=>x.Name==dtField.Name);
如果(字段!=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(十进制))
{
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);
}
其他的
{
propertyInfos.SetValue
(classObj,ConvertToString(dataRow[dtField.Name]),null);
}
}
}
}
dataList.Add(classObj);
}
返回数据列表;
}
私有静态字符串ConvertToDateString(对象日期)
{
如果(日期==null)
返回字符串。空;
返回SpecialDateTime.ConvertDate(Convert.ToDateTime(date));
}
私有静态字符串ConvertToString(对象值)
{
返回Convert.ToString(HelperFunctions.returnEmptyIfFull(value));
}
私有静态整型转换(对象值)
{
返回Convert.ToInt32(HelperFunctions.ReturnZeroIfNull(value));
}
私有静态长转换(对象值)
{
返回Convert.ToInt64(helperFunction.ReturnZeroIfNull(值));
}
私有静态十进制ConvertToDecimal(对象值)
{
返回Convert.ToDecimal(HelperFunctions.ReturnZeroIfNull(value));
}
私有静态日期时间convertToDateTime(对象日期)
{
return Convert.ToDateTime(HelperFunctions.ReturnDateTimeMinIfNull(date));
}
}
最后,我需要这样称呼它:
List List=dt.ToList
但是此代码不起作用虽然不太清楚您想要实现什么,但是您可以使用
dynamic
关键字和System.dynamic.ExpandoObject
with.Net>=4来完成您描述的操作。在类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);
}
}
公共类ICF
{
公共静态列表icfList=新列表();
#区域
公共int标志{get;set;}
公共字符串ClaimID{get;set;}
公共字符串代码{get;set;}
公共字符串PlotNumber{get;set;}
公共字符串RyotNumber{get;set;}
公共字符串RyotName{get;set;}
公共字符串ClaimDate{get;set;}
公共字符串ClaimFormNo{get;set;}
公共字符串声明{get;set;}
公共字符串{get;set;}
公共字符串ClaimReason{get;set;}
公共字符串测量器ID{get;set;}
公共字符串测量器日期{get;set;}
公共字符串保险金额{get;set;}
#端区
公共静态void AddRow(DataRow dr)
{
ICF obj=新的ICF();
obj.Flag=Convert.ToInt32(dr[“Flag]”);
obj.ClaimID=dr[“ClaimID”].ToString();
obj.RyotNumber=dr[“RyotNumber”].ToString();
obj.seasurecode=dr[“seasurecode”].ToString();
obj.PlotNumber=dr[“PlotNumber”].ToString();
obj.RyotNumber=dr[“RyotNumber”].ToString();
obj.RyotName=dr[“RyotName”
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>
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);
}
}
[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";
}
}