The right thing would be to turn this lot of properties into a collection (array, list or similar).
public class Teste
{
public List<int> Campos { get; } = new List<int>();
}
So you don’t need to change the model every time you need a new field, plus it seems to make a lot more sense.
To use, you can do so:
var obj = new Teste();
for(int i = 0; i <= 8; i++)
{
obj.Campos.Add(i);
}
See working on . NET Fiddle.
If you really can’t do this, you’ll have to use reflection, basically you’ll need the method SetValue
of PropertyInfo
.
For example:
var obj = new Teste();
string propBase = "campo_";
for(int i = 1; i <= 8; i++)
{
var propName = propBase + i;
typeof(Teste).GetProperty(propName).SetValue(obj, i, null);
}
See working on . NET Fiddle.
I don’t see what this has to do with model, anyway, it’s simple, make it a list, array, or something like that, which is the right thing to do, after all it is clear that this is unique information with variants, it is the clear example that variables should be encapsulated into a single variable. If you can’t do this, then you’ll have to think about it, and it’ll be a huge gambit.
– Maniero
Model is a class no?! so it’s still the same...
– Peres
@Ronaldoperes It’s not.
– Jéf Bueno
So this isn’t a model? class Data { public string dailyDealId { get; set; } public string discountPercentage { get; set; } public Array product { get; set; } }
– Peres