把从CSV中读出内容进行解析,写入到实体类中 class TestClass { public static void Main(string[] arge) { Msg msg = new Msg(); string [] title = "\"AAA\",\"BBB\",\"CCC\",\"DDD\"".Replace("\"", "").Replace("\t", "").Split(',');//读取到的表头 string [] value = "\"3227\",\"2008133740090886\",\"123456\",\"2020-08-13 13:40:53\"".Replace("\"", "").Replace("\t", "").Split(',');//读取到表头下边的内容。 msg = StringToEntityClass(msg, title, value); Console.ReadLine(); } /// <summary> /// 把字符串根据标题数据动态赋值到实体类中 /// </summary> /// <typeparam name="T">动态类型</typeparam> /// <param name="t">实体类</param> /// <param name="title">标题数组,大小写必须和实体类的字段值一样</param> /// <param name="Valus">对应的值</param> /// <returns></returns> public static T StringToEntityClass<T>(T t,string [] title,string [] Valus) { var type = t.GetType().GetProperties(); for (int i = 0; i < type.Length; i++) { for (int j = 0; j < title.Length; j++) { if (type[i].Name.ToUpper() == title[j]) { type[i].SetValue(t, ConversionType(type[i].PropertyType, Valus[j]) , null); continue; } } } return t; } public static object ConversionType(Type type, string v) { if (type == typeof(int)) { return int.Parse(v); } if (type == typeof(DateTime)) { return Convert.ToDateTime(v); } if (type == typeof(DateTime?)) { return Convert.ToDateTime(v); } if (type == typeof(string)) { return v; } return v; } } //实体类型 仅供参考 public class Msg { public int AAA { get; set; } public string BBB { get; set; } public string CCC { get; set; } public DateTime DDD { get; set; } } |
|