您的位置:首页 > 编程语言 > C#

【C#】从文本获取实体对象

2017-11-24 10:12 239 查看
/// <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# 字符串转对象