using System.Data; using System.Reflection; using Newtonsoft.Json; namespace SparkClient.Model.Helper; public class Common { public const string DatabasePwd = "DyumL4FvF6wVHWw"; public const string AesKey = "JbI36Snd3s+QjlOcz5dytgkL5W6OnFEV5ZNRg/OYp58="; public const string AesIV = "QRYL9P9NcV9Uny29DqEBqg=="; public static readonly string BasePath = AppDomain.CurrentDomain.BaseDirectory; public const string DataBaseFileName = "SparkDB.db"; public const string DataBaseTempFileName = "SparkDBtemp.db"; public const string DataBaseName = "SparkDB"; /// /// 将 DataTable 转换为 JSON 字符串 /// /// 要转换的 DataTable /// JSON 字符串 public static string DataTableToJson(DataTable table) { if (table == null) { throw new ArgumentNullException(nameof(table), "DataTable cannot be null."); } return JsonConvert.SerializeObject(table, Formatting.Indented); } /// /// 将 JSON 字符串转换为 DataTable /// /// 要转换的 JSON 字符串 /// 还原的 DataTable public static DataTable JsonToDataTable(string json) { if (string.IsNullOrEmpty(json)) { throw new ArgumentNullException(nameof(json), "JSON string cannot be null or empty."); } return JsonConvert.DeserializeObject(json); } /// /// 将 DataTable 转换为实体对象列表 /// /// 目标实体类型 /// 要转换的 DataTable /// 实体对象列表 public static List ConvertToEntityList(DataTable table) where T : new() { if (table == null) { throw new ArgumentNullException(nameof(table), "DataTable cannot be null."); } var entityList = new List(); // 获取实体类型的所有属性 var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (DataRow row in table.Rows) { // 创建实体对象 var entity = new T(); foreach (var property in properties) { // 检查 DataTable 是否包含与属性名匹配的列 if (table.Columns.Contains(property.Name) && row[property.Name] != DBNull.Value) { // 设置实体属性值 property.SetValue(entity, Convert.ChangeType(row[property.Name], property.PropertyType)); } } entityList.Add(entity); } return entityList; } }