覆盖抽象列表<a> property with list</a> <a>

时间:2018-01-03 09:57:48

标签: c# abstract overrides

I'm writing a piece of code to make certain reports. There are 4 types of reports which the user can request. Each type report is based on the base class 'report'. Each derived class has a List. The class 'A' is derived from base class 'a'.

Is it possible to add an abstract List to the 'report' class and let it be overridden by a List in the derived report classes? Something like this?

public abstract class Report
{
  public abstract List<a> Coils { get; set; }
}

public class ProductionExitCoilReport : Report
{
  public override List<A> Coils { get; set; }             
}

public class a
{
  public string SomeProperty { get; set; }
}

public class A: a
{
  public string SomeOtherProperty { get; set; }             
}

I'm kind of new to C# so if I'm asking something really basic or I have a big flaw in my thinking, please do point it out. But please don't just answer with yes or no.

2 个答案:

答案 0 :(得分:2)

根据您对用法的描述,无需覆盖新类中的List / collection。由于A继承自a,因此可以在“Coils”中存储类型A的对象。 (由于多态性)。然后,如果稍后您想要访问A类对象的“SomeOtherProperty”,则可以使用强制转换。

public abstract class Report
{
    public List<a> Coils { get; set; }
}

public class ProductionExitCoilReport : Report
{

}

public class a
{
    public string SomeProperty { get; set; }
}

public class A : a
{
    public string SomeOtherProperty { get; set; }
}

public void SomeMethod()
{
    //to store the coil
    ProductionExitCoilReport myReport = new ProductionExitCoilReport();
    myReport.Coils.Add(new A());

    //to retreive SomeOtherProperty from the first element in the list
    string retrievedProperty = ((A)myReport.Coils[0]).SomeOtherProperty;
}

答案 1 :(得分:0)

您的属性是可读写的。

派生类型必须始终与基本类型兼容。

每个Report都有Coils属性,该属性返回类型为a的项目的读/写集合。因此,您始终可以写report.Coils.Add(new a())

ProductionExitCoilReport继承自Report,因此可以运行相同的代码 - 将a(不是A)添加到{{返回的集合中1}}:Coils

这与你想要完成的事情相矛盾。

请阅读covariance and contravariance