C#泛型和派生

C#泛型和派生,c#,generics,derived-class,C#,Generics,Derived Class,我已经翻阅了好几篇关于这个主题的帖子,没有找到以下问题的合适答案 有谁能告诉我为什么这不能编译: class MyItem { public int ID; } class MyList<T> { public List<T> ItemList; } class MyDerivedItem : MyItem { public string Name; } class MyDerivedList<MyDerivedItem> : My

我已经翻阅了好几篇关于这个主题的帖子,没有找到以下问题的合适答案

有谁能告诉我为什么这不能编译:

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
    }
}
类MyItem{
公共int ID;
}
类MyList{
公共清单项目清单;
}
类MyDerivedItem:MyItem{
公共字符串名称;
}
类MyDerivedList:MyList{
公共整数GetID(整数索引){
return ItemList[index].ID;//错误:MyDerivedItem不包含ID的定义
}
公共字符串GetName(int索引){
return ItemList[index].Name;//错误:MyDerivedItem不包含名称的定义
}
}

您对此有一些问题,首先是您的通用签名

虽然
class MyDerivedList:MyList
可能看起来像是使用
MyDerivedItem
作为类型的泛型类声明,但实际上您只是声明了一个使用
MyDerivedItem
作为泛型类型参数名称的泛型类

您要查找的是
类MyDerivedList:MyList,其中T:MyDerivedItem
,它将把您的第一个问题转换为下一个问题,即您的其他类型的属性对于此类型来说不够可访问

class MyItem
{
    public int ID;
}
class MyList<T>
{
    public List<T> ItemList;
}

class MyDerivedItem : MyItem
{
    public string Name;
}

这应该可以编译得很好。

乔纳森的答案是正确的,但可能提出的解决方案并不完全是你想要的

可能您只是想要继承封闭泛型类型的非泛型类型:

class MyDerivedList : MyList<MyDerivedItem>

但是现在,
T
是一个泛型类型参数,而不是具体类型这一事实是显而易见的

更正了“公开”的拼写错误。这显然不是编译器所抱怨的…谢谢你的选择,但约翰纳顿的回答确实是我想要实现的。
class MyDerivedList : MyList<MyDerivedItem>
 class MyDerivedList : MyList<MyDerivedItem>
 {
    int GetID(int index)
    {
        return ItemList[index].ID;
    }

    string GetName(int index)
    {
        return ItemList[index].Name; 
    }
}
class MyDerivedList<T> : MyList<T>