我有一个类,其中有十几个表示各种财务领域的属性。我还有另一个类需要单独对每个字段执行一些计算。这些计算方法内部的代码除了执行计算的字段不同之外都完全相同。
是否可以传递属性名称作为参数,并只使用一个方法来执行所有工作,而不是为每个属性编写12个方法?
此外,我确定可以通过反射实现这一点,但我在其他代码中看到过使用lambda完成相同工作的方式,并且想知道这是否是可以使用lambda的候选项。
如请求的那样,这里是一个示例:
是否可以传递属性名称作为参数,并只使用一个方法来执行所有工作,而不是为每个属性编写12个方法?
此外,我确定可以通过反射实现这一点,但我在其他代码中看到过使用lambda完成相同工作的方式,并且想知道这是否是可以使用lambda的候选项。
如请求的那样,这里是一个示例:
public class FinancialInfo
{
public virtual DateTime AuditDate { get; set; }
public virtual decimal ReleasedFederalAmount { get; set; }
public virtual decimal ReleasedNonFederalAmount { get; set; }
public virtual decimal ReleasedStateAmount { get; set; }
public virtual decimal ReleasedLocalAmount { get; set; }
public virtual decimal ReleasedPrivateAmount { get; set; }
// more fields like this
}
public class FinancialLedger()
{
public virtual DateTime? BeginDate { get; set; }
public virtual DateTime? EndDate { get; set; }
public virtual IList<FinancialInfo> Financials { get; set; } //not actual implementation, but you get the idea
public decimal GetTotalReleasedFederalAmountByDate()
{
if (BeginDate == null && EndDate == null)
return 0;
decimal total = 0;
foreach (var fi in Financials)
{
if (someCondition)
if (someSubCondition)
total += fi.ReleasedFederalAmount;
else if (someOtherCondition)
if (someOtherSubCondition)
total += fi.ReleasedFederalAmount;
else if (anotherCondigion)
total += fi.ReleasedFederalAmount;
}
return total;
}
public decimal GetTotalReleasedNonFederalAmountByDate()
{
// same logic as above method,
// but it accesses fi.ReleasedNonFederalAmount;
}
// More methods the same as the previous, just accessing different
// members of FinancialInfo
}
我的目标是只创建一个名为GetTotalAmountByDate()的方法,并传入开始日期、结束日期以及需要访问的属性名称(例如: ReleasedFederalAmount 或 ReleasedLocalAmount等)。
我希望这准确地描述了我想要实现的内容。