直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
List<TestModel> testList = new List<TestModel>(); testList.Add(new TestModel { Id = 1, Name = "A" }); testList.Add(new TestModel { Id = 2, Name = "B" }); testList.Add(new TestModel { Id = 3, Name = "C" }); List<dynamic> test = new List<dynamic>(); foreach (var item in testList) { dynamic dobj = new System.Dynamic.ExpandoObject(); var dic = (IDictionary<string, object>)dobj; var t = item.GetType(); var properties = t.GetProperties(); // 循环赋值原Model中的值 foreach (var propertyInfo in properties) { var propertyName = propertyInfo.Name; dic[propertyName] = propertyInfo.GetValue(item); } // 动态扩展属性 dic["Age"] = 3; test.Add(dic); } |
示例Model
1 2 3 4 5 |
public class TestModel { public int Id { get; set; } public string Name { get; set; } } |