[英]Using a Sort Method for a collection of objects in an Abstract Class
我有一個抽象類,它定義了許多可以投票然后排序的類。 由於這些類都共享它們被排序的屬性,我想在抽象級別包含一個方法,讓我按這些屬性對它們進行排序,但是我遇到了“不能賦值給參數”的錯誤。
我該如何處理以下事項:
internal abstract class ESCO
{
public double HotScore { get; set; }
public double VoteTotal { get; set; }
public DateTime Created { get; set; }
protected static List<ESCO> SortedItems(List<ESCO> escoList, ListSortType sortType)
{
switch (sortType)
{
case ListSortType.Hot:
escoList.Sort(delegate(ESCO p1, ESCO p2) { return p2.HotScore.CompareTo(p1.HotScore); });
return escoList;
case ListSortType.Top:
escoList.Sort(delegate(ESCO p1, ESCO p2) { return p2.VoteTotal.CompareTo(p1.VoteTotal); });
return escoList;
case ListSortType.Recent:
escoList.Sort(delegate(ESCO p1, ESCO p2) { return p2.Created.CompareTo(p1.Created); });
return escoList;
default:
throw new ArgumentOutOfRangeException("sortType");
}
}
private SPUser GetCreatorFromListValue(SPListItem item)
{
var user = new SPFieldUserValue(SPContext.Current.Web, (string)item["Author"]);
return user.User;
}
private static VoteMeta InformationForThisVote(List<Vote> votes, int itemId)
{} // There are more methods not being shown with code to show why I used
// abstract instead of something else
}
試圖這樣實現:
class Post : ESCO
{
public string Summary { get; set; } // Properties in addition to abstract
public Uri Link { get; set; } // Properties in addition to abstract
public static List<Post> Posts(SPListItemCollection items, ListSortType sortType, List<Vote> votes)
{
var returnlist = new List<Post>();
for (int i = 0; i < items.Count; i++) { returnlist.Add(new Post(items[i], votes)); }
return SortedItems(returnlist, sortType);
}
我完全願意“你做錯了”。
我無法重現相同的錯誤消息,但我認為你得到的錯誤是因為
return SortedItems(returnlist, sortType);
正在嘗試返回抽象基類的列表。 嘗試將其更改為
return SortedItems(returnlist, sortType).Cast<Post>().ToList();
如果您還沒有,則需要包含System.Linq命名空間。
僅供參考,我得到的錯誤(在簡化的測試案例中)是
Cannot implicitly convert type System.Collections.Generic.List<MyNamespace.ESCO>' to 'System.Collections.Generic.List<MyNamespace.Post>'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.