设置违反开闭原则验证的属性值
本文关键字:验证 属性 原则 设置 | 更新日期: 2023-09-27 18:02:00
我有一个ServiceField
类,其中包含FieldId
和Value
作为两个属性。
public class ServiceField
{
public int FieldId { get; set; }
public string Value { get; set; }
}
/// <summary>
/// This method is used to assign value to HajjPackageFields class
/// </summary>
/// <param name="hajPackageObj">HajjPackageFields whose value needs to be updated</param>
private void UpdateDetailFieldsValue(HajjPackageFields hajPackageObj)
{
foreach (ServiceField field in GetPackageDetails(hajPackageObj.PackageId))
{
if (field.FieldId == (int)HajjServiceFieldsEnum.AccomodationView)
{
hajPackageObj.AccomodationView = field.Value == "1";
}
else if (field.FieldId == (int)HajjServiceFieldsEnum.AirTicket)
{
hajPackageObj.AirTicket = field.Value == "1";
}
}
}
问题是,如果在HajjPackageField
类添加任何新的属性,我必须修改我的UpdateDetailFieldsValue
方法,这是反对开闭原则。有没有其他合适的方法来完成这个任务?
如果我清楚地理解了你,反思将有助于解决问题:
private void UpdateDetailFieldsValue(HajjPackageFields hajPackageObj)
{
var pairs = new Dictionary<int, string>();
foreach (var enumVal in typeof(HajjServiceFieldsEnum).GetEnumValues())
pairs[(int)(HajjServiceFieldsEnum)enumVal] = typeof(HajjServiceFieldsEnum).GetEnumName(enumVal);
foreach (ServiceField field in GetPackageDetails(hajPackageObj.PackageId))
typeof(HajjPackageFields).GetProperty(pairs[field.FieldId])
?.SetValue(hajPackageObj, field.Value == "1");
}