我无法访问基类的属性?

时间:2018-08-04 13:22:21

标签: c#

我在这里有一个简单的课程

class Leader : Inhabitants
{

    public int ProducedWorth { get; set; }
    public Leader(string name, int age, string profession, int producedWorth)
    {
        InhabitantID = InhabitantCount;
        Name = name;
        Age = age;
        Profession = profession;
        ProducedWorth = producedWorth;
    }
    public int GetProducedWorth()
    {
        return ProducedWorth;
    }
}
从居民类继承的

 class Inhabitants
{
    static protected int InhabitantCount;
    public Inhabitants()
    {
        InhabitantCount++;
    }
    public int InhabitantID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Profession { get; set; }
}

现在,当我创建该类的新实例时,它似乎工作得很好,但是当我尝试访问仅位于基类上的producedWorth属性时,我得到了继承类没有所述属性的错误?

var leadA = new Leader("Julien", 33, "Stone pit overseer", 6540)
//leadA.Name is accessible
//leadA.producedWorth is not accessible

program.cs

3 个答案:

答案 0 :(得分:2)

该列表是一个居民列表,您只能访问居民的属性,原因是编译器不知道列表中的实际对象是Leader类型,尽管您可以通过转换为Leader来告诉他:

((Leader)leadA).ProducedWorth

上面的行应该编译。

答案 1 :(得分:0)

通用列表是协变的,这就是为什么允许您将Leader添加到Inhabitants列表中的原因。

允许隐式转换,您不必使用var。这样做:

foreach(Leader ldr in leaders)
{
   // ....
}

答案 2 :(得分:-2)

在您执行的代码中,您将创建一个不具有属性ProducedWorth的Inhabitants类型列表。如果您希望能够以这种方式访问​​它,则需要将该属性添加到Inhabitants类中。