2017-12-27 397 views
1

我試圖循環訪問不同屬性的設置次數的一行數據每次。循環通過循環中的屬性

的數據是這樣的:

[JsonProperty("Afbeelding")] 
    public string Afbeelding { get; set; } 

    [JsonProperty("Afbeelding_2")] 
    public string Afbeelding2 { get; set; } 

    [JsonProperty("Afbeelding_3")] 
    public string Afbeelding3 { get; set; } 

    [JsonProperty("Afbeelding_4")] 
    public string Afbeelding4 { get; set; } 

    [JsonProperty("Afbeelding_5")] 
    public string Afbeelding5 { get; set; } 

    [JsonProperty("Afbeelding_6")] 
    public string Afbeelding6 { get; set; } 

    [JsonProperty("Afbeelding_7")] 
    public string Afbeelding7 { get; set; } 

我試着在循環中的folllowing:

var path = CreateFile(profitImageRow.("Afbeelding"+i), profitImageRow.Bestandsnaam+i); 

第一個沒有編制,而第二個只會增加我的價值「Bestandsnaam」

有沒有什麼辦法讓這項工作在循環中?

+0

的可能的複製[獲得從使用C#反射字符串屬性值](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c -尖銳) – mjwills

回答

0

首先,你的JSON應該已經被反序列化爲Dictionary<string, string>,然後Key就是你的_X屬性,值也會在那裏。

如果你不能(或不會)改變模型,你可以使用反射的力量。

E.g.

var props = typeof(MyModel).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.Name.StartsWith("Afbeelding")); 

foreach(var prop in props) 
{ 
    var value = prop.GetValue(modelHere); //now value has the corresponding string. 
} 

// Or you can do 
for(int i =1 ; i < 8; i++){ 
    var neededProp = props.FirstOrDefault(x => x.Name == $"Afbeelding_{i}"); //now this has the value 
}