覆盖抽象list property with list

问题描述 投票:-1回答:2

我正在编写一段代码来制作某些报告。用户可以请求有4种类型的报告。每种类型的报告都基于基类“报告”。每个派生类都有一个List。类'A'派生自基类'a'。

是否可以在“报告”类中添加一个抽象列表,并让它在派生报告类中被List覆盖?像这样的东西?

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

我对C#有些新意,所以如果我问一些非常基本的东西,或者我的想法有很大的缺陷,请指出来。但请不要只回答是或否。

c# abstract overrides
2个回答
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;
}

0
投票

您的属性是可读写的。

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

每个Report都有Coils属性,返回a类型的读/写集合。因此,你总是可以写report.Coils.Add(new a())

ProductionExitCoilReport继承自Report,因此可以运行相同的代码 - 将a(而不是A)添加到Coils返回的集合:((Report)productionReport).Coils.Add(new a())

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

请阅读有关covariance and contravariance的信息:

© www.soinside.com 2019 - 2024. All rights reserved.