【问题标题】:Read all rows and properties from List<T> [duplicate]从 List<T> 中读取所有行和属性 [重复]
【发布时间】:2020-07-02 22:19:18
【问题描述】:
    public string ClassListToText<T>(List<T> obj)
    {
        StringBuilder str = new StringBuilder();
        PropertyInfo[] properties = typeof(T).GetProperties();
        foreach(PropertyInfo property in properties)
        {
            str.Append(property.Name + "|");
        }
        str.Append(">>");

        foreach (T row in obj)
        {
            string txtRow = string.Empty;
            foreach (PropertyInfo property in properties)
            {
                txtRow += row[property.Name].ToString().Trim();
                txtRow += "|";
            }
            txtRow += ">";
            str.AppendLine(txtRow);

        }
        return str.ToString();
    }

我想读取所有列表行和属性并将其写入文本文件。我找不到如何执行这部分代码“row[property.Name]”?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    你可以使用PropertyInfo.GetValue:

    txtRow += property.GetValue(row).ToString().Trim();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多