C#迭代类属性

我目前正在设置我的类对象Record所有值。

这是我现在用来填充logging的代码,属性是财产。

 // Loop through each field in the result set for (int i = 0; i <= resultItems.Length; i++) { Record newRecord = new Record() { itemtype = resultItems[i - (fieldCount - 0)], itemdesc = resultItems[i - (fieldCount - 1)], prodcode = resultItems[i - (fieldCount - 2)], proddesc = resultItems[i - (fieldCount - 3)], curstat = resultItems[i - (fieldCount -4)], totfree = resultItems[i - (fieldCount -5)], totphys = resultItems[i - (fieldCount -6)], pcolgroup = resultItems[i - (fieldCount -7)], scolgroup = resultItems[i - (fieldCount -8)], totpo = resultItems[i - (fieldCount - 9)], totso = resultItems[i - (fieldCount - 10)], quality = resultItems[i - (fieldCount - 11)], statusdesc = resultItems[i - (fieldCount - 12)], groupcode = resultItems[i - (fieldCount - 13)], qualitydes = resultItems[i - (fieldCount - 14)], pcoldesc = resultItems[i - (fieldCount - 15)], scoldesc = resultItems[i - (fieldCount - 16)], pgroupdesc = resultItems[i - (fieldCount - 17)], }; } 

我可以迭代通过每个属性dynamic而不硬编码所有的属性名称?

像这样的东西:

 // Create new Record instance Record newRecord = new Record(); for (int e = 0; e < propertyCount.Length - 1; e++) { newRecord[fieldname] = resultItems[i - (fieldCount - e)]; } 

你可以使用reflection来做到这一点。 据我所知,你可以枚举你的类的属性并设置值。 你将不得不尝试一下,并确保你了解属性的顺序。 有关此方法的更多信息,请参阅此MSDN文档 。

对于一个提示,你可能会做一些事情:

 Record record = new Record(); PropertyInfo[] properties = typeof(Record).GetProperties(); foreach (PropertyInfo property in properties) { property.SetValue(record, value); } 

value是你想要写入的值(所以从你的resultItems数组)。

 // the index of each item in fieldNames must correspond to // the correct index in resultItems var fieldnames = new []{"itemtype", "etc etc "}; for (int e = 0; e < fieldNames.Length - 1; e++) { newRecord .GetType() .GetProperty(fieldNames[e]) .SetValue(newRecord, resultItems[e]); } 

是的,您可以在您的Record类上创build一个索引器,从属性名称映射到正确的属性。 这将保留从属性名称到属性的所有绑定,例如:

 public class Record { public string ItemType { get; set; } public string this[string propertyName] { set { switch (propertyName) { case "itemType": ItemType = value; break; // etc } } } } 

另外,正如其他人所说,使用reflection。