How to change the value of a property given its name

Asked

Viewed 801 times

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 in a Combobox one of the options you want to change, in this Combobox are the strings "alpha", "beta" and "gamma".

So I need to perform 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 the switch. But the problem is that the functions are not so simple, they are large codes, and with the switch It gets very repetitive and whenever I need to change something I have to move a lot of places. I would like to do this more automatically.

2 answers

6

You can use a combination of:

  • PropertyInfo: Allows observation and handling of type characteristics;
  • Convert.ChangeType: Allows the change of types who implement IConvertible between formats during runtime.

For example, your instance Class1.alfa could have the property dado dynamically amended 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);

0

I do not know if it is possible to execute directly in this format. What would work is you check which value of the variable change and use an if, with the definitions since there are few comparisons, getting more or less 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 don’t know if in C# there is such a method.

  • The problem is that there are not a few comparisons. This was just an example of the functionality I need so I don’t have to put in too much code.

  • So I can’t help :(

  • If I’m not mistaken, in Java you can also use Reflection to do the same thing, using the class Field: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.