jeudi 11 juin 2020

Iterate through Nested Classes and Transform Property, Multiple Int by 2

The goal of this code is to iterate through multiple nested classes, and multiple any integer by 2. Provided simple example, however, example will be more complicated in future.

How do I change a Object to its underlying class? When I iterate through this function, it reads the type for OuterProduct correctly, but fails for InnerProduct reading as type System.RuntimeType, giving an error below

How can I resolve this code to multiply all nested integers by 2?

An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.

class Program
{
    static void Main(string[] args)
    {
        var test = new OuterProduct();
        test.AmountSold = 5;
        test.ProductName = "BookOuter";

        test.InnerProduct = new InnerProduct();
        test.InnerProduct.ProductNameInner = "BookInner";
        test.InnerProduct.AmountSoldInner = 7;

        ReadPropertiesTest.ReadPropertiesRecursive(test);
    }
}

public class OuterProduct
{
    public string ProductName { get; set; }
    public int AmountSold { get; set; }
    public InnerProduct InnerProduct { get; set; }
}

public class InnerProduct
{
    public string ProductNameInner { get; set; }
    public int AmountSoldInner { get; set; }
}

public static class ReadPropertiesTest
{
    public static void ReadPropertiesRecursive(object test)
    {
        var type = test.GetType();

        foreach (PropertyInfo property in type.GetProperties())
        {
            if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
            {
                property.SetValue(test, (int)(property.GetValue(test)) * 2);
            }
            if (property.PropertyType.IsClass && !(property.PropertyType == typeof(string)))
            {
                ReadPropertiesRecursive(property.PropertyType);
            }
        }
    }
}

Resources:

C#: How to get all public (both get and set) string properties of a type

How to iterate through nested properties of an object





Aucun commentaire:

Enregistrer un commentaire