在这里,我提出了第一种方法:即在DataSet上使用foreach子句来获取项并填写实体。但是,当某些内容发生变化时,不能重用此方法。
因此,我认为,也许反思应该是我的方案的最佳方法。详情如下:
1.我的实体定义如下:
using System.ComponentModel;
namespace WarningServiceForYM.Model
{
public class StuffEntity
{
[Description("企业ID")]
public string EnterpriseID { get; set; }
[Description("冰柜编号")]
public string FridgeID { get; set; }
[Description("冰柜名称")]
public string FridgeName { get; set; }
[Description("手机号码")]
public string PhoneNumber { get; set; }
[Description("设备名称")]
public string EquipmentName { get; set; }
[Description("采集参数")]
public string PickingParams { get; set; }
[Description("一路温度")]
public string TempOne { get; set; }
[Description("二路温度")]
public string TempTwo { get; set; }
[Description("三路温度")]
public string TempThree { get; set; }
[Description("四路温度")]
public string TempFour { get; set; }
[Description("五路温度")]
public string TempFive { get; set; }
[Description("六路温度")]
public string TempSix { get; set; }
[Description("七路温度")]
public string TempSeven { get; set; }
[Description("八路温度")]
public string TempEight { get; set; }
[Description("温度最低")]
public string Min { get; set; }
[Description("温度最高")]
public string Max { get; set; }
[Description("采集时间")]
public string PickingTime { get; set; }
[Description("通知间隔")]
public string WarningPeriod { get; set; }
[Description("延时")]
public string PendingTime { get; set; }
[Description("通知开关")]
public string Switch { get; set; }
[Description("最后通知时间")]
public string LastInformTime { get; set; }
}
}
我已经将这个数据集的数据保存到csv文件中,请单击此处查找它。
StuffEntity中的内部属性与DataSet中的列标题具有相同的描述。
有人会给我一个方法来演示如何将这个数据集转换为StuffEntity吗?谢谢。
发布于 2013-10-11 01:07:10
好的,使用反射:
public static T GetEntity<T>(DataRow row) where T : new()
{
var entity = new T();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
//Get the description attribute
var descriptionAttribute = (DescriptionAttribute)property.GetCustomAttributes(typeof(DescriptionAttribute), true).SingleOrDefault();
if (descriptionAttribute == null)
continue;
property.SetValue(entity, row[descriptionAttribute.Description]);
}
return entity;
}你可以像这样使用它:
foreach (DataRow dataRow in dataSet.Tables[0].Rows)
{
var e = GetEntity<StuffEntity>(dataRow);
Console.WriteLine(e.EnterpriseID);
}它是一个通用实现,因此您可以将它与任何其他类型或数据集一起使用。我注意使它尽可能简单,这样就可以广泛地改进添加一些一致性,比如在设置实体值之前检查列名是否存在,或者根据需要验证重复的描述。例如,还可以将其转换为DataRow、DataTable或DataSet的扩展方法。
https://stackoverflow.com/questions/19286246
复制相似问题