我有一个抽象类,它定义了许多可以投票并排序的类。由于这些类都共享排序所依据的属性,我希望在抽象级别包含一个方法,使我能够根据这些属性对它们进行排序,但我遇到了"不可分配给参数"错误的问题。
我应该如何处理以下问题:
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();
您需要包含系统。Linq命名空间(如果您还没有)。
仅供参考,我得到的错误(在一个简化的测试用例中)是
Cannot implicitly convert type System.Collections.Generic.List<MyNamespace.ESCO>' to 'System.Collections.Generic.List<MyNamespace.Post>'