c# - 一种将一个列表转换为另一个列表的方法(通过多态性、子类和父类)

标签 c# asp.net-mvc inheritance collections polymorphism

好吧,所以我有以下方法:

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/

相关文章:

javascript - 如何在javascript中将init参数传递给基类

java - 接口(interface)真的可以用来实现多重继承吗

c++ - 虚拟友元函数和模板显式特化

c# - 如何引用 Windows.Gaming.Input 命名空间

javascript - 如何在 cshtml 页面中将选项传递给 JavaScript

c# - 我怎样才能找出 kernelbase.dll 中的错误是什么?

c# - 使用多对多关系添加对象 Entity Framework

如果继承 BaseController,带有 OnException 的 ASP.NET MVC4 Controller 不起作用

c# - HTTPPost 不工作 asp mvc 3

c# - 开始使用 MVC 创建大型 C# 应用程序的最佳方法是什么?