2
我寫我工作的一個系統的CSV導入引擎和我清理執行想避免樣的代碼看起來像(重複10的列):路過的時候屬性的方法
var field = GetFieldStringValue(columnCode);
if (IsValidDecimal(field))
{
currentRow.Amount = Decimal.Parse(field);
}
else
{
ReportError();
}
在我選擇看起來像這樣(與重載各種類型)的方法,所述端:
private void SetPropertyOrReportError(Action<decimal?> e, string columnCode)
{
if (IsValidDecimal(columnCode))
{
var fieldValue = Decimal.Parse(GetFieldStringValue(columnCode));
e(fieldValue);
}
else if (!IsColumRequired(columnCode))
{
e(null);
}
else
{
SetPropertyOrReportError();
}
}
這樣對於每一行我最終代碼有點像這樣:
var currentRow = new ClaimImportHelper();
SetPropertyOrReportError((e) => currentRow.ClaimantName = e, ClaimantNameColumnCode);
SetPropertyOrReportError((e) => currentRow.CustomerName = e, CustomerNameColumnCode);
SetPropertyOrReportError((e) => currentRow.CustomerProject = e, CustomerProjectColumnCode);
SetPropertyOrReportError((e) => currentRow.ClaimDate = e.Value, ClaimDateColumnCode);
SetPropertyOrReportError((e) => currentRow.ClaimSubmitted = e, ClaimSubmittedColumnCode);
SetPropertyOrReportError((e) => currentRow.ExpenseCategory = e, ExpenseCategoryColumnCode);
SetPropertyOrReportError((e) => currentRow.ExpenseType = e, ExpenseTypeColumnCode);
SetPropertyOrReportError((e) => currentRow.Amount = e.Value, AmountColumnCode);
SetPropertyOrReportError((e) => currentRow.PayeeReference = e, PayeeReferenceColumnCode);
SetPropertyOrReportError((e) => currentRow.Detail = e, DetailColumnCode);
SetPropertyOrReportError((e) => currentRow.TransactionDate = e, TransactionDateColumnCode);
parsedItems.Add(currentRow);
我認爲這是更好的,因爲它表達更好的意圖。然而,它仍然不是因爲我想它是,我寧願能夠調用這樣的方法:
SetPropertyOrReportError(currentRow.ClaimantName, ClaimantNameColumnCode);
SetPropertyOrReportError(currentRow.CustomerName, CustomerNameColumnCode);
SetPropertyOrReportError(currentRow.CustomerProject, CustomerProjectColumnCode);
SetPropertyOrReportError(currentRow.ClaimDate, ClaimDateColumnCode);
SetPropertyOrReportError(currentRow.ClaimSubmitted, ClaimSubmittedColumnCode);
我遇到的問題是,我不能左右我的頭如何編寫一個表達式來獲取屬性。我怎樣才能做到這一點?