我有一个Job
类,如下所示:
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; }
}
现在我想计算作业object
的校验和。此校验和的目的是指示作业的任何属性是否已被修改。。。所以我想构建一个包含所有属性值的字符串,并获得这个字符串的校验和:
[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();
}
问题是GetValue()
没有正确获得复杂类型(即SalaryRange
(的值,它返回了类的名称空间,即stringifiedValues
的值为:
"Civil EngineerMySolutionName.ProjectName.FolderName"
是否可以覆盖或更改GetValue()
的行为以返回嵌套属性的字符串化值?
它获取的值很好;的问题是该值是一个SalaryRange
实例,而默认的object.ToString()
实现是写入类型名称。你可以忽略它:
public class SalaryRange
{
public decimal MinSalary { get; set; }
public decimal MaxSalary { get; set; }
public override string ToString() => $"{MinSalary}-{MaxSalary}"; // for example
}