How to iterate in a C # model with variables that have number?

-2

I have a model that was made by another developer where it has several fields like this:

. . .

Teste() teste = new Teste();
teste.campo_1 = 1;
teste.campo_2 = 2;
teste.campo_3 = 3;
teste.campo_4 = 4;
teste.campo_5 = 5;

How would you fill in the data using for?

    
asked by anonymous 16.01.2018 / 18:51

2 answers

2

As Maniero said in his comment , you need to use reflection for do that. If you can not make the modifications that he suggested, the following code works and can help you.

public class Teste
{
    public int campo_1 { get; set; }
    public int campo_2 { get; set; }
    public int campo_3 { get; set; }
    public int campo_4 { get; set; }
    public int campo_5 { get; set; }
}

public class Example
{
    public static void Main()
    {
        var teste = new Teste();
        var type = teste.GetType();
        var properties = type.GetProperties();

        foreach (var property in properties)
        {
            var valor = property.Name.Substring(property.Name.IndexOf("_") + 1);

            Console.WriteLine("Propriedade: " + property.Name);
            Console.WriteLine("Valor antes: " + property.GetValue(teste, null));

            property.SetValue(teste, Int32.Parse(valor));

            Console.WriteLine("Valor depois: " + property.GetValue(teste, null));
            Console.WriteLine();
        }
    }
}

See also working here

    
16.01.2018 / 19:23
5

The right thing would be to transform this bunch of properties into a collection (array, list, or similar).

public class Teste
{
    public List<int> Campos { get; } = new List<int>();
}

So you do not have to change the template every time you need a new field, and it seems to make a lot more sense.

To use, you can do this:

var obj = new Teste();
for(int i = 0; i <= 8; i++)
{
    obj.Campos.Add(i);
}

See working in .NET Fiddle.

If you really can not do this, you'll have to use reflection, you'll basically 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 in .NET Fiddle.     

16.01.2018 / 19:28