【发布时间】:2014-11-22 02:58:02
【问题描述】:
我有一些代码对于几种不同的数据类型重复完全相同。我想将其简化为一种通用方法,但我无法弄清楚如何做到这一点。我之前发过这个,显示了很大一部分实际代码:Exact same code repeated multiple times for different data types; Any way to make one function that can handle all possible types?
这就是我希望我的通用函数做的事情。我知道我写的不正确,但我认为这应该可以说明我的意图:
private List<LinkData> ProcessSections(<T> sections)
{
if (sections != null)
{
foreach (var item in sections)
{
tempLD = new LinkData();
tempLD.Text = item.SectionTitle;
tempLD.Class = "class=\"sub-parent\"";
autoData.Add(tempLD);
if (item.Link != null && item.Link.Length > 0)
{
foreach (var child in item.Link)
{
tempLD = new LinkData
{
Text = child.a.OuterXML,
Link = child.a.href,
Class = "class=\"\""
};
autoData.Add(tempLD);
}
}
}
}
return autoData;
}
sections 可以是四种可能的数据类型,但所有四种的使用方式完全相同;特定的数据类型仅取决于需要如何反序列化 XML 页面。这些是四种类型:MaintainedPageLeftContentAdditionalSection[]、StandardPageLeftContentAdditionalSection[]、StoryPageLeftContentAdditionalSection[] 和 DoctorPageLeftContentAdditionalSection[]。这里有两个例子,你可以看到它们的功能基本相同。
public partial class MaintainedPageLeftContentAdditionalSection
{
private string sectionTitleField;
private MaintainedPageLeftContentAdditionalSectionLink[] linkField;
/// <remarks/>
public string SectionTitle
{
get
{
return this.sectionTitleField;
}
set
{
this.sectionTitleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Link")]
public MaintainedPageLeftContentAdditionalSectionLink[] Link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
}
public partial class StandardPageLeftContentAdditionalSection
{
private string sectionTitleField;
private StandardPageLeftContentAdditionalSectionLink[] linkField;
/// <remarks/>
public string SectionTitle
{
get
{
return this.sectionTitleField;
}
set
{
this.sectionTitleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Link")]
public StandardPageLeftContentAdditionalSectionLink[] Link
{
get
{
return this.linkField;
}
set
{
this.linkField = value;
}
}
}
那么,如何创建一个可以接受任何 AdditionalContent 类型的通用函数?
【问题讨论】:
-
每个预期的类型都可以派生自一个公共类/接口吗?