实体类:
public class TestObj
    {
        public string A1 { get; set; }
        public string A2 { get; set; }
        public string A3 { get; set; }
        public string A4 { get; set; }
        public string A5 { get; set; }
  }
读取数据库值后,赋值到LIST,
资源代下载得到Listt数据集合。

目前,想遍历,就是类似这样:Listt[i].A1,其中的1可以循环,就是循环读取其中实体类中的变量。(为了方便封装)

试了下,Listt[i].A+i.ToString(),提示:
"TestObj”未包含“A”的定义,并且找不到可接受第一个“TestObj”类型参数的可访问扩展方法“A"

怎么做,谢谢!

msdn baidu google 搜索一下反射。

反射也可以,
用datatable接收循环也是个方案。

然而我觉得这种,没必要去封装。

虽然脱裤子放屁但是还是满足楼主给你个简单的方法:

怎么遍历读取实体类的变量名?

怎么遍历读取实体类的变量名?

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        List<Test> ListT = new List<Test>();

        private void Form1_Load(object sender, EventArgs e)

        {

            for (int i = 0; i < 4; i++)

            {

                Test Ts = new Test();

                Ts.A1 = "我是A1值是" + i;

                Ts.A2 = "我是A2值是" + i;

                Ts.A3 = "我是A3值是" + i;

                Ts.A4 = "我是A4值是" + i;

                ListT.Add(Ts);

            }

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            richTextBox1.Text = "";

            List<string> ListString = ListZh(ListT);

            foreach (var item in ListString)

            {

                for (int i = 0; i < item.Split('|').Length; i++)

                {

                    richTextBox1.Text += item.Split('|')[i];

                    richTextBox1.Text += "\r\n";

                }

            }

        }

        public List<string> ListZh(List<Test> ListTs)

        {

            List<string> ListString = new List<string>();

            foreach (var item in ListTs)

            {

                string Pj = "";

                Pj += item.A1+"|";

                Pj += item.A2 + "|";

                Pj += item.A3 + "|";

                Pj += item.A4;

                ListString.Add(Pj);

            }

            return ListString;

        }

    }

}

因为有很多类似的报表需要做,类似的实体类,循环后赋值给excel文件,所以想封装。

谢谢,我查下。

那我觉得用datatable来更方便

特性了解下,当然,还是要用到反射.

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-17
  • 2022-03-05
  • 2023-01-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案