2017-12-27 369 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 
}