C#反射List<T>调用Add方法

举个之前做过工具中找过的代码 在这里列举部分 自行修改 即可使用 这里主要是介绍List<T>调用 Add 方法:

一个类实例 gameData 中有一个 List<T>的成员(Field 我就把他叫成员了)

//这段可以忽略 就是要获得list这个成员信息 FieldInfo

FieldInfo fInfo = gameData.GetType().GetField(ToLowerFirst(className) + "List");

//列表类型

Type classListType = fInfo.FieldType;

//根据成员的类型创建列表 List<T> list = new List<T>();
object entityList = Activator.CreateInstance(classListType);

BindingFlags flag = BindingFlags.Instance | BindingFlags.Public;
MethodInfo methodInfo = classListType.GetMethod("Add", flag);
methodInfo.Invoke(entityList, new object[] { obj });//相当于List<T>调用Add方法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,如果您想要遍历 DataTable dtzz 并返回一个 List<result> 类型的集合,可以按照以下步骤进行操作: 1. 定义一个 List<result> 类型的集合,用于存储遍历结果: ``` List<result> results = new List<result>(); ``` 2. 遍历 DataTable dtzz,并将每行数据转换为 result 类型的实例,并添加到集合中: ``` foreach (DataRow row in dtzz.Rows) { result r = new result(); r.property1 = row["column1"].ToString(); r.property2 = int.Parse(row["column2"].ToString()); // ... results.Add(r); } ``` 其中,result 是您自定义的类型,需要根据实际需求定义,并且需要根据表结构和数据类型来访问 DataRow 中的数据。 3. 返回集合: ``` return results; ``` 完整示例代码如下: ``` using System; using System.Collections.Generic; using System.Data; class Program { static void Main(string[] args) { // 调用方法获取结果集合 List<result> results = GetData(); // 输出结果集合 foreach (result r in results) { Console.WriteLine(r.property1); Console.WriteLine(r.property2); // ... } } static List<result> GetData() { List<result> results = new List<result>(); // 假设 dtzz 是一个 DataTable 类型的对象 DataTable dtzz = new DataTable(); // 添加列和数据行 foreach (DataRow row in dtzz.Rows) { result r = new result(); r.property1 = row["column1"].ToString(); r.property2 = int.Parse(row["column2"].ToString()); // ... results.Add(r); } return results; } } class result { public string property1 { get; set; } public int property2 { get; set; } // ... } ``` 注意,这里只是一个示例,您需要根据实际情况修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值