c# - C# 泛型和派生
问题描述
我一直在挖掘有关此主题的几篇帖子,但找不到以下问题的任何合适答案……</p>
谁能告诉我为什么这不能编译:
class MyItem {
public int ID;
}
class MyList<T> {
public List<T> ItemList;
}
class MyDerivedItem : MyItem {
public string Name;
}
class MyDerivedList<MyDerivedItem> : MyList<MyDerivedItem> {
public int GetID(int index) {
return ItemList[index].ID; // ERROR : MyDerivedItem does not contain a definition for ID
}
public string GetName(int index) {
return ItemList[index].Name; // ERROR : MyDerivedItem does not contain a definition for Name
}
}
解决方案
您对此有一些问题,首先是您的通用签名。
虽然class MyDerivedList<MyDerivedItem> : MyList<MyDerivedItem>
看起来像是使用MyDerivedItem
作为类型的泛型类声明,但实际上您只是声明了一个使用MyDerivedItem
泛型类型参数名称的泛型类。
您正在寻找的是class MyDerivedList<T> : MyList<T> where T : MyDerivedItem
,它将您的第一个问题交换为您的下一个问题,即您的其他类型的属性对于这个问题来说不够可访问。
class MyItem
{
public int ID;
}
class MyList<T>
{
public List<T> ItemList;
}
class MyDerivedItem : MyItem
{
public string Name;
}
好的,现在可以从MyDerivedList
类中访问这些属性,但还有最后一个问题需要纠正。int GetName(int index)
应该是string GetName(int index)
,因为该Name
属性是一个字符串。
这导致以下结果:
class MyDerivedList<T> : MyList<T> where T : MyDerivedItem
{
int GetID(int index)
{
return ItemList[index].ID;
}
string GetName(int index)
{
return ItemList[index].Name;
}
}
哪个应该编译得很好。
推荐阅读
- python - 张量流张量的最大值在轴上的位置
- c - 如何修复“分段错误(核心转储)”?
- excel - 数据透视表排序 - 类别而不是“值”
- javascript - 如何使用 ListStyle.heroCard 将自定义数据添加到 ChoicePrompt
- python - 我如何让不和谐的机器人存储来自 DM 的消息,但只有在他们在服务器中完成命令后
- tensorflow - ImportError:DLL 加载失败,错误代码 3221225501 tensorflow
- python - 需要将单词月份转换为表格中的数字
- jspdf - didCellParse 不返回单元格
- sql - 使用 SQL 重新格式化多特征时间序列数据
- android - Android SortedList 拖动并重新排序项目抛出 IndexOutOfBoundsException:检测到不一致。无效的视图支架适配器 positionViewHolde