我有兩個幾乎完全相同的c#函數。因爲他們非常相似,所以我想我會試用泛型,但我很難理解如何去做。任何建議,還是我完全吠叫錯誤的樹?如何使用c#泛型重寫這兩個幾乎相同的函數?
public IList<UnitTemplate> UnitTemplates { get; set; }
public IList<QualTemplate> QualTemplates { get; set; }
public QualTemplate FindQualTemplate(string templateID)
{
QualTemplate selectedQualTemplate;
if (QualTemplates.Count == 0)
throw new CreatioException("This user's brand has no QualTemplates. There must be at least one available.");
if (QualTemplates.Count == 1 || String.IsNullOrEmpty(templateID))
selectedQualTemplate = QualTemplates.First();
else
selectedQualTemplate = QualTemplates.Single(x => x.QualTemplateID.ToLower() == templateID.ToLower());
if (selectedQualTemplate == null)
throw new CreatioException(String.Format("No QualTemplate with the id {0} could be found for this user's brand.", templateID));
return selectedQualTemplate;
}
public UnitTemplate FindUnitTemplates(string templateID)
{
UnitTemplate selectedTemplate;
if (UnitTemplates.Count == 0)
throw new CreatioException("This user's brand has no UnitTemplates. There must be at least one available.");
if (UnitTemplates.Count == 1 || String.IsNullOrEmpty(templateID))
selectedTemplate = UnitTemplates.First();
else
selectedTemplate = UnitTemplates.Single(x => x.UnitTemplateID.ToLower() == templateID.ToLower());
if (selectedTemplate == null)
throw new CreatioException(String.Format("No UnitTemplate with the id {0} could be found for this user's brand.", templateID));
return selectedTemplate;
}
與你的問題無關,但我認爲你應該使用'x.QualTemplateID.Equals(templateID,StringComparison.OrdinalIgnoreCase)'而不是'ToLower'。 – Timwi 2010-10-14 12:01:52
感謝提示,Timwi! – centralscru 2010-10-14 13:13:33