vendredi 4 décembre 2020

Is it possible to override GetValue() method for complex types?

I have a Job class as below:

public class Job
{
    public string JobTitle { get; set; }
    public SalaryRange SalaryRange { get; set; }
}

public class SalaryRange
{
    public decimal MinSalary { get; set; }
    public decimal MaxSalary { get; set; }
}

Now I want to calculate the checksum of job object. The purpose of this checksum is to indicate if any property of job has been modified... so I want to build a string which contains all of its property values and get the checksum of this string:

[TestMethod]
public void Calculate_job_checksum()
{
    var salary = new SalaryRange()
    {
        MinSalary = 15,
        MaxSalary = 20
    };
    
    vat job = new Job()
    {
        JobTitle= "Civil Engineer",
        SalaryRange = salary
    };
    
    string stringifiedValues = "";
    PropertyInfo[] properties = job.GetType().GetProperties();
    foreach (PropertyInfo p in properties)
    {
        if (p.CanRead))
        {
            // combine all values
            var val = p.GetValue(job);
            stringifiedValues += val.ToString();
        }
    }

    // get the checksum
    jobChecksum = stringifiedValues.GetChecksum();
}

The problem is GetValue() does not get the value of the complex type (i.e. SalaryRange) correctly, it returns the namespace of the class, i.e. the value of stringifiedValues is:

"Civil EngineerMySolutionName.ProjectName.FolderName"

Is it possible to override or change the behavior of GetValue() to return stringified values of nested properties?





Aucun commentaire:

Enregistrer un commentaire