/// <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#】将text文本转换为实体对象list
于 2017-11-24 10:12:23 首次发布