- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
虽然我环顾四周,但没有找到任何与我的问题完全匹配的东西 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/
System.Collections.ObjectModel.KeyedCollection 类是 System.Collections.Generic.Dictionary 的一个非常有用的替代品,
我是 C# 的新手,如果这是一个愚蠢的问题,请原谅我。我遇到错误,但我不知道如何解决。我正在使用 Visual Studio 2010。 这行代码 public class GClass1 : Key
我想创建一个方法来遍历键控集合。我想确保我的方法支持迭代任何扩展 KeyedCollection> 的集合 方法如下: public void IterateCollection(KeyedColle
虽然我环顾四周,但没有找到任何与我的问题完全匹配的东西 this肯定是接近的。基本上,我有一个 Page 对象的 KeyedCollection 作为基础,我希望派生对象的强类型集合来自它。具体来说,
我有一个类 (SomeClass),它包含 string 类型的属性 Name。我需要存储该类的数组并按名称查找其项。为此,有两种类型的集合:KeyedCollection 和Dictionary。我
我正在开发一个 C# 对象复制构造函数,其中一部分涉及将 KeyedCollection 的内容复制到新的 KeyedCollection 中。这是我目前实现的: class MyKeyedColle
首先让我解释一下为什么我要使用 KeyedCollection。我正在构建一个 DLL,我有一个项目列表,我需要将它们添加到一个集合中,并让它们保持我放置它们的顺序,但我还需要通过它们的索引和键来访问
我正在寻找一种与通用字典的 Keys 属性(KeyCollection 类型)一样高效的方法。 使用 Linq select 语句可以,但每次请求键时它都会遍历整个集合,而我相信键可能已经存储在内部。
我有这段代码(我希望它能工作,但它失败了)。我真的不知道为什么。请帮忙 static void Main(string[] args) { var x = new M
我想使用 KeyedCollection 来存储一个针对字符串键值的类。我有以下代码: public class MyClass { public string Key; public
我认为这是我们遇到的一个常见问题。 class Person { public string place; public string name; public Person(
我是 WPF 数据绑定(bind)的初学者,我刚刚发现了一种令人困惑的行为。也许有人可以帮助我: 我的 xaml 代码将列表框绑定(bind)到列表: 如果绑定(bind)的实际项目是一个列表,一切
基本上我有一个 KeyedCollection ,并且我希望能够按键(或者最好使用自定义比较器)对集合进行排序。 如果这不可能,有人可以推荐另一个类,其中键嵌入在我可以排序的值中吗? 最佳答案 根据更
我经常需要一组带有数字标识符的非顺序对象。我喜欢为此使用 KeyedCollection,但我认为有一个严重的缺点。如果您使用 int 作为键,您将无法再通过索引访问集合的成员(collection[
我有课 public class FooKeyedCollection : KeyedCollection { } public enum FooType { FooType1, FooT
是否存在与 C# 抽象 KeyedCollection 类具有相同行为的 Java 集合(即可以通过键和索引检索项目)?我环顾四周,但找不到类似的东西。 谢谢,尼克 最佳答案 这是使用“KeyedIt
请参阅下面的 VS2013 更新。 将类用作 d:DesignInstance 时暴露了 KeyedCollection ,XAML 设计器发出以下警告: The number of generic
我是一名优秀的程序员,十分优秀!