我正在寻求结合两个具有相似代码但变量类型不同的函数。我想在IEnumerable中使用T类型,但它似乎不起作用。
方法1:
public static IList<ListItem> AppendTopMakesToList(this IEnumerable<ListItem> options,bool appendSeparatorRow = true)
{
if (options == null || string.IsNullOrEmpty(Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes"))) return options.ToList();
var topmakes = Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes").Split('|').ToList().ConvertAll(d => d.ToLower());
var filteredMakes = options.Where(x => topmakes.Any(y => y.Contains(x.Text.ToLower()))).ToList();//getting all the makes from the listItems
if (appendSeparatorRow)
{
var separatorListItem = new ListItem("------------------", "------------------", false);
separatorListItem.Attributes.Add("disabled", "true"); //disabling the separator item so that it can't be selected
filteredMakes.Add(separatorListItem);
}
var items = options.ToList();
items.InsertRange(0, filteredMakes);
return items;
}
方法2:
public static IList<Make> AppendTopMakesToList(this IEnumerable<Make> options, bool appendSeparatorRow = true)
{
if (options == null || string.IsNullOrEmpty(Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes"))) return options.ToList();
var topmakes = Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes").Split('|').ToList().ConvertAll(d => d.ToLower());
var filteredMakes = options.Where(x => topmakes.Any(y => y.Contains(x.Code.ToLower()))).ToList();//getting all the makes from the listItems
if (appendSeparatorRow)
{
var separatorListItem = new Make()
{
Code = "------------------",
Description = "------------------"
};
filteredMakes.Add(separatorListItem);
}
var items = options.ToList();
items.InsertRange(0, filteredMakes);
return items;
}
这些函数的作用与返回类型IList和IList完全相同,后者是通过IEnumberable和IEnumberable的参数类型传递的。
答案 0 :(得分:2)
我会做类似的事情:
public static IList<T> AppendItems<T>(this IEnumerable<T> options, Action<T> blankFactory, bool appendSeparatorRow = true)
{
if (options == null || string.IsNullOrEmpty(Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes"))) return options.ToList();
var topmakes = Sitecore.Configuration.Settings.GetSetting("RACQ.JoinMembership.Top10CarMakes").Split('|').ToList().ConvertAll(d => d.ToLower());
var filteredMakes = options.Where(x => topmakes.Any(y => y.Contains(x.Code.ToLower()))).ToList();//getting all the makes from the listItems
if (appendSeparatorRow)
{
var separatorListItem = blankFactory();
filteredMakes.Add(separatorListItem);
}
var items = options.ToList();
items.InsertRange(0, filteredMakes);
return items;
}
然后您可以像这样使用它:
var whatever = new List<ListItem>():
AppendItems(whatever, () => {
var separatorListItem = new ListItem("------------------", "------------------", false);
separatorListItem.Attributes.Add("disabled", "true");
return separatorListItem;
}, true);