How to change the value of a property given its name

4

In my program I have some classes where data is stored. For example

Class1.alfa.dado = 66;
Class1.beta.dado = 56;
Class1.gama.dado = 37;

The user will select one of the options that you want to change in a ComboBox, in this ComboBox are the alpha, beta and gamma strings.

So I need to run a function that does more or less like this

void change (string alterar)
{
    Class1.(alterar).dado = 7;
}

How to use this "change" string to access the variable?

One solution would be to use switch . But the problem is that the functions are not so simple, they are big codes, and with switch gets very repetitive and whenever I need to change something I have to get into a lot of places. I would like to do this more automatically.

    
asked by anonymous 18.08.2014 / 14:38

2 answers

6

You can use a combination of:

  • PropertyInfo : Enables the observation and manipulation of type characteristics;
  • Convert.ChangeType : Lets you change types that implement IConvertible between formats during runtime.

For example, your Class1.alfa instance could have the dado property changed dynamically as follows:

string propriedade = "dado";
string valor = "66";

PropertyInfo propertyInfo = Class1.alfa.GetType().GetProperty(propriedade);
propertyInfo.SetValue(Class1.alfa, Convert.ChangeType(valor, propertyInfo.PropertyType), null);
    
18.08.2014 / 16:08
0

I do not know if it's possible to run directly in this format. What would work if you check the value of the variable to change and use an if, with the definitions since there are few comparisons, going something like this:

void change (string alterar)
{
    if ("gama".toString(alterar)){
        Class1.gama.dado = 7;
    }
    if ("beta".toString(alterar)){
        Class1.beta.dado = 7;
    }
    if ("alfa".toString(alterar)){
        Class1.alfa.dado = 66;
    }
}

When writing the answer, I thought I was in a JAVA question, since it was a tag that was open in my browser ... I do not know if in C # there is this method.

    
18.08.2014 / 15:29