gpt4 book ai didi

c# - 派生类的通用 KeyedCollection

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:09 25 4
gpt4 key购买 nike

虽然我环顾四周,但没有找到任何与我的问题完全匹配的东西 this肯定是接近的。基本上,我有一个 Page 对象的 KeyedCollection 作为基础,我希望派生对象的强类型集合来自它。具体来说,我有:

public class Page
public class Category : Page
public class PageList<T> : KeyedCollection<string, T> where T : Page
public class CategoryList : PageList<Category>

现在,这看起来很好,直到我想从 PageList<T> 中调用一个方法。使用类似 DoSomethingTo(this) 的东西当前声明为 DoSomethingTo(PageList<Page> pageList) .这给了我一个转换错误。

正如您可能已经想到的那样,我希望能够使用 DoSomething(this)来自 PageList<T> CategoryList 类中的 类。

我该怎么做……或者我该怎么做?我尝试了与上面链接的问题中建议的方法类似的方法,但我什么也做不了。谢谢!

最佳答案

你的问题是PageList<Page>PageList<Category>不是协变的。它们实际上是完全不相关的类型。即使 T 是派生类型,生成的泛型集合也不是。

如果你仔细想想,这是正确的,否则就没有什么能阻止你通过 CatagoryList 了。到一个需要 PageList 的函数然后可以添加 Page到无效的类别集合。

为了帮助处理这种情况,C# 4 添加了对协变接口(interface)的支持。这些通过使用 in 和 out 关键字来限制您可以做的事情,从而允许有限的协变。

您的链接问题使用了这个,您也可以这样做。

interface IPageList<out T> where T : Page
{
}

public class PageList<T> : KeyedCollection<string, T>, IPageList<T> where T : Page
{
}


DoSomethingTo(IPageList<Page> pageList)
{
}

关于c# - 派生类的通用 KeyedCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22036210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com