我有一個要求,用戶從下拉列表中選擇一個ReportType並點擊下載按鈕。根據他選擇的類型,系統應該生成一個報告。現在我只有報表類型,即QuoteReport。將來我會有其他報告類型,如PolicyReport,ClaimReport。現在我不知道這些報告中的數據字段是什麼。如何創建一個通用的類結構
public class QuoteReport
{
public String DeviceType { get; set; }
public String ProductName { get; set; }
public String Description { get; set; }
public String ID { get; set; }
public String Address { get; set; }
}
現在我正在做的是發送報告類型和參數來填充報告,我創建了一個開關案例來捕獲被選擇的報告類型。
public string PrepareReport(string selectedReport, List<int> Ids)
{
string response = string.Empty;
try
{
ReportTypeEnum reportTypeEnum;
if (Enum.TryParse(selectedReport, out reportTypeEnum))
{
switch (reportTypeEnum)
{
case ReportTypeEnum.QuoteReport:
response = CreateReportData(Ids,response);
break;
default:
break;
}
}
}
catch (Exception exc)
{
handleException(DOWNLOAD_REPORT, exc);
}
return response;
}
我的方法CreateReportData從wcf填充QuoteReport類的字段。
public string CreateReportData(List<int> Ids, string response)
{
List<QuoteReport> quoteReportList = new List<QuoteReport>();
foreach (var Id in Ids)
{
dynamic dynamicEntity;
List<string> devices = proxy.GetData(Id);
for (int i = 0; i < devices.Count; i++)
{
QuoteReport quoteReport = new QuoteReport();
dynamicEntity = JObject.Parse(devices[i]);
quoteReport.Type = dynamicEntity.DeviceTypeString;
quoteReport.ProductName = dynamicEntity.ProductName;
quoteReport.Description = dynamicEntity.Desc;
quoteReport.ID = dynamicEntity.ID;
assetReport.Address = dynamicEntity.Address;
quoteReportList.Add(quoteReport);
}
}
response = JsonConvert.SerializeObject(quoteReportList);
return response;
}
現在我很困惑我該如何讓我的代碼更通用。或者我是否可以使用Factory等設計模式來使代碼適應未來需求。如何使CreateReportData方法成爲通用的,以便它接受任何類類型並從服務中填充其屬性。
問題在當前狀態下對於SO來說太不明確/寬泛。在重構之前等待,直到你真正知道你的用例,這可能是個好主意。爲單個案例編寫通用代碼很困難,並且在介紹其他案例時可能無用。 –
@AlexeiLevenkov我應該使用任何設計模式來創建一個結構 – pankaj
不要使用開關 - 使用'Dictionary>'(或類似的東西)來啓用動態創建不同的類型。此外,請永遠不要編寫catch(Exception exc)' - 你應該**只會發現可以專門從中恢復的錯誤。 –
Enigmativity