/// <summary> /// Gets the list from string. /// </summary> /// <typeparam name="T">输出类型</typeparam> /// <param name="str">The string.</param> /// <param name="separator">字符串分隔符</param> /// <returns></returns> public static List<T> GetListFromString<T>(string str, char separator) { try { byte[] array = Encoding.UTF8.GetBytes(str); MemoryStream stream = new MemoryStream(array); StreamReader reader = new StreamReader(stream); string lineStr; List<T> ResultList = new List<T>(); while ((lineStr = reader.ReadLine()) != null) //按行读取文件 { T model = Activator.CreateInstance<T>(); string[] fields = lineStr.Split(new char[] { separator }); //切割字符串 PropertyInfo[] proInfos = model.GetType().GetProperties(); //获取所有属性 for (int i = 0; i < fields.Length; i++) { proInfos[i].SetValue(model,fields[i]); //对每一个属性赋值 } ResultList.Add(model); } return ResultList; } catch (Exception ex) { throw ex; } }
【C#】从文本获取实体对象
最新推荐文章于 2023-01-29 10:54:58 发布