好吧,所以我有以下方法:
private List<Store> NextPrevious(List<Store> model, int numFields, int page, ref bool nextRef, ref bool previousRef)
{
if (model.Count > numFields && page == 0)
{
model = model.Skip(page * (numFields - 1)).Take(numFields - 1).ToList();
next = true;
previous = false;
}
else if (page > 0 && model.Skip(page + (numFields - 2)).Count() <= (numFields - 1))
{
model = model.Skip(page + (numFields - 2)).Take(numFields - 1).ToList();
next = false;
previous = true;
}
else if (page > 0 && model.Count > (page + 1))
{
model = model.Skip(page + (numFields - 2)).Take(numFields - 2).ToList();
next = true;
previous = true;
}
return model.ToList();
}
我会这样调用该方法:
model.Groups = NextPrevious(model.Groups.ToList<Store>(), 3, groupPage, ref next, ref previous);
model.Groups
类型为List<Group>
。 Group
是一个类的子类 Store
。现在,当我在方法( ref
)中发送该组时,有没有办法引用该组,或者至少返回它,就像我尝试过的那样,但没有成功,并使其正常工作。现在,如果我输入此内容并尝试运行它,我会收到错误:
Cannot implicitly convert type 'System.Collections.Generic.List<(path)Store> to 'System.Collections.Generic.List<(path)Group>'
我知道该错误意味着什么,但我只是不具备解决该错误的知识,所以我在这里寻求帮助。顺便说一句,我无法将其转换为 return model.ToList<Group>()
两者都不是,因为该方法是创建的,所以它可以用于继承Store
的其他类对象。类。
谢谢!
最佳答案
解决方案可能是更改 NextPrevious
作为generic method并声明以下内容constraint关于类型参数:
private List<T> NextPrevious<T>(List<T> model, int numFields, int page, ref bool nextRef, ref bool previousRef) where T:Store
{
//...
}
这样你只需要这样做:
model.Groups = NextPrevious(model.Groups, 3, groupPage, ref next, ref previous);//call model.Groups.ToList() in case the Groups property is not a List<Group>
您可以在调用NextPrevious<T>
时省略类型参数。方法,因为编译器将根据您传递的第一个方法参数推断它。
关于c# - 一种将一个列表转换为另一个列表的方法(通过多态性、子类和父类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908905/