首页 > 解决方案 > 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
    }
}

标签: c#genericsderived-class

解决方案


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

虽然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; 
    }
}

哪个应该编译得很好。


推荐阅读