dimanche 28 février 2021

Update property of baseclass from derived class

I need to update a property in a base class through various derived classes, from a parent class.

This is my working code I'm using in LinqPad that will demonstrate the issue better.

void Main()
{
    var setting = typeof(Setting);
    PropertyInfo[] props = setting.GetProperties();
    
    string basePathValue = @"C:\my\path";
    
    foreach (var prop in props)
    {
        if (prop.PropertyType.IsSubclassOf(typeof(MyBase)))
        {
            // ???
            // string fullyQualifiedName = prop.PropertyType.FullName + ", " + assemName;
            // var t = (MyBase)Type.GetType(fullyQualifiedName);  // this doesn't work
            // t.BasePath = basePathValue;

            Console.WriteLine($"Name: {prop.PropertyType}");
            /*
            
            returns:
            Name: Customer
            Name: Profile
            
            */
            
            // How do I update the 'BasePath' property of each class
            // that inherits from MyBase and return the new
            // Setting class with the updated values?
        }
    }
    
    /*
    The result I want is:
    
    var customer = setting.Customer;
    var customerBasePath = customer.BasePath;
    // customerBasePath == "C:\my\path"
    */
}

// You can define other methods, fields, classes and namespaces here
public abstract class MyBase
{
    public string BasePath { get; set; }
}

public class Customer : MyBase
{
    
}

public class Profile : MyBase
{
    
}

public class Product
{
    
}

public class Setting
{
    public Customer Customer { get; set; }
    public Profile Profile { get; set; }
    public Product Product { get; set; }
}

I need to update the BasePath property in both the Customer and Profile classes, and then get an instance of the Setting class with the BasePath property values set.

I think it needs to be done via Reflection because other class properties could be added to Setting in the future and I would need to have all the class property's BasePath properties set.

Any guidance is appreciated.





Aucun commentaire:

Enregistrer un commentaire