用列表<A>覆盖抽象列表<a> 属性
Overriding abstract list<a> property with list<A>
我正在编写一段代码来制作某些报告。用户可以请求 4 种类型的报告。每种类型的报告都基于 class 'report' 的基础。每个派生 class 都有一个列表。 class 'A' 派生自基础 class 'a'.
是否可以向 'report' class 添加一个抽象列表,并让它在派生报告 classes 中被一个列表覆盖?是这样的吗?
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# 的新手,所以如果我问的是一些非常基础的问题,或者我的想法有很大缺陷,请指出。但请不要只回答是或否。
根据您对用法的描述,无需覆盖新 class 中的 List/collection。由于A继承自a,所以可以在"Coils"中存储A类型的对象。 (由于多态性)。然后,如果在稍后的某个时间,您想要访问 "SomeOtherProperty" 类型 A 的对象,您可以使用强制转换。
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;
}
您的属性是可读可写的。
派生类型必须始终与基类型兼容。
每个 Report
都有 Coils
属性 returns 个 read/write 类型 a
的项目集合。因此你总是可以写 report.Coils.Add(new a())
.
ProductionExitCoilReport
继承自 Report
,因此可以 运行 相同的代码 - 添加 a
(而不是 A
) Coils
返回的集合:((Report)productionReport).Coils.Add(new a())
.
这与您想要实现的目标相矛盾。
我正在编写一段代码来制作某些报告。用户可以请求 4 种类型的报告。每种类型的报告都基于 class 'report' 的基础。每个派生 class 都有一个列表。 class 'A' 派生自基础 class 'a'.
是否可以向 'report' class 添加一个抽象列表,并让它在派生报告 classes 中被一个列表覆盖?是这样的吗?
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# 的新手,所以如果我问的是一些非常基础的问题,或者我的想法有很大缺陷,请指出。但请不要只回答是或否。
根据您对用法的描述,无需覆盖新 class 中的 List/collection。由于A继承自a,所以可以在"Coils"中存储A类型的对象。 (由于多态性)。然后,如果在稍后的某个时间,您想要访问 "SomeOtherProperty" 类型 A 的对象,您可以使用强制转换。
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;
}
您的属性是可读可写的。
派生类型必须始终与基类型兼容。
每个 Report
都有 Coils
属性 returns 个 read/write 类型 a
的项目集合。因此你总是可以写 report.Coils.Add(new a())
.
ProductionExitCoilReport
继承自 Report
,因此可以 运行 相同的代码 - 添加 a
(而不是 A
) Coils
返回的集合:((Report)productionReport).Coils.Add(new a())
.
这与您想要实现的目标相矛盾。