简体   繁体   中英

how to get values of generic object in generic object list C#

I need help for get a object values, this object is in an object list, for example.

list<object> objectList = new list<object>();
objectList.Add( new {  id = 1,  name = "name1"});
objectList.Add( new {  id = 2,  name = "name2"});

the problem is I can't get the values of these objects inside the list, and put their values in a excel file, I tried this.

int row = 2
for(int i = 0; row < objectList ; i++){
 excelRow[row,1].Value = item[i].id
 excelRow[row,2].Value = item[i].name
row++
}

You can use an implicitly typed array to create an array that's actually typed to the anonymous type that you're using:

var objectList = new []
{
    new {  id = 1,  name = "name1"},
    new {  id = 2,  name = "name2"},
};

Once you've done that when you get an item from the collection it's actually it's real type (which has no name) rather than object .

动态对象可以满足此要求

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM