How to set the values of a Propertyinfo of the instantiated classes within a class?

Asked

Viewed 92 times

-1

I am doing a generic method for rounding values of a class(T), but I also have the classes within this principal(T), these classes I can set in this way:

IEnumerable<PropertyInfo> childrenProperties = entidade.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(model => model.PropertyType.Namespace == typeof(T).Namespace).ToArray();

I wonder how to get the values of these classes, with the main class(T) I just do so:

    foreach (var propertie in decimalPropertiesModel)
    {
        var value = propertie.GetValue(entidade, null);

        if (value != null)
        {
            propertie.SetValue(entidade, decimal.Round((decimal)value, noCasasDecimais), null);
        }
    }

But with the other classes I can’t do the same.

Remembering that this is a generic method, I have the main class Centrotrabalhoonline, I can set all properties and their values of this class, but within this class I also have the class Centrotrabalho, want to know how to set the properties and their values of this class Centrotrabalho.

  • I don’t understand the problem, is it giving error or unexpected result? Where do you get it and where not? The problem is not at another point, ie what you are getting (decimalPropertiesModel) in this part is wrong? I may be wrong but there seems to be no error there.

  • "value rounding of a class(T), but I also have the classes within that principal(T)" - I didn’t notice. Shows a class that serves as an example of input, and shows the output desired.

  • What do you mean, "take the values of these classes"? What values are these? What classes are these?

  • I edited the description of the question at the end.

1 answer

0

If I understand correctly, you have a class that has a mixture of normal properties (from int, double, decimal, etc.) and class properties (of Class1, OutroClasse, etc..).

If you want to access the properties of all classes, you will need to create a recursive function. I don’t have exactly what it would be like, but use the next code to inspire you:

public void Recursiva(Type tipo, object entidade) {
    foreach ( prop in entidade.GetType().GetProperties() ) {
       var value = prop.GetValue( entidade, null );
       if ( value is decimal ) {
          //faz algo com decimal
       } else {
          //chama o Recursiva de novo:
          Recursive(value.GetType(), value );
       }
    }
}
  • Cool @brazilianldsjaguar, really it is this way, I will see if I can implement something like this and return when possible, ta half run here rs, hugs !!

Browser other questions tagged

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