[英]C# Iterate through Class properties
我目前正在設置我的類對象Record
所有值。
這是我目前用來逐個屬性地填充記錄的代碼。
// 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)],
};
}
我可以在不硬編碼所有屬性名稱的情況下動態迭代每個屬性嗎?
像這樣:
// Create new Record instance
Record newRecord = new Record();
for (int e = 0; e < propertyCount.Length - 1; e++)
{
newRecord[fieldname] = resultItems[i - (fieldCount - e)];
}
你可以使用反射來做到這一點。 據我了解,您可以枚舉類的屬性並設置值。 您必須嘗試一下,並確保您了解屬性的順序。 有關此方法的更多信息,請參閱此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]);
}
我嘗試了塞繆爾·斯萊德 (Samuel Slade ) 的建議。 沒有為我工作。 PropertyInfo
列表是空的。 所以,我嘗試了以下方法,它對我有用。
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
是的,您可以在 Record 類上創建一個索引器,從屬性名稱映射到正確的屬性。 這會將所有從屬性名稱到屬性的綁定保存在一個地方,例如:
public class Record
{
public string ItemType { get; set; }
public string this[string propertyName]
{
set
{
switch (propertyName)
{
case "itemType":
ItemType = value;
break;
// etc
}
}
}
}
或者,正如其他人提到的,使用反射。
添加到Samuel Slade對任何選擇這種方法的人的回應(這很好)。 考慮兩件事:
話雖如此,請特別注意沒有 setter 方法的屬性,如下所示:
public string Username { get; set; }
public bool HasCar
{
get
{
return this.Car != null;
}
}
這里第一個屬性將能夠設置為指定的值,但第二個屬性不能設置,因為它沒有 setter 方法。 我為解決這個問題所做的是在屬性上使用 GetSetMethod() 來區分那些沒有 setter 方法的屬性,如下所示:
var properties = this.GetType().GetProperties();
foreach(var prop in properties)
{
if(prop.GetSetMethod() != null) {
prop.SetValue(this, null);
};
}
希望這條評論可以為您節省一些時間!
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.