多年来,这一直是我沮丧的根源。我的理解是,当一个类继承或以其他方式从另一个基类派生时,它可以从一个方法返回,该方法的签名将基类指定为它的返回值。由于根据定义,派生类必须也是基类,因此应该没有问题。这对我不起作用,也从未对我起作用,所以我一直在寻找解决方法,而不是理解为什么这是不正确的以及“正确”的解决方案是什么。
public abstract class Contract
{
[Key]
[DataMember]
[Column("Id")]
public Int64 Id { get; set; }
[DataMember]
[Column("ContactName")]
[DataType(DataType.Text)]
public String ContactName { get; set; }
[DataMember]
[DataType(DataType.EmailAddress)]
[Column("ContactEmail")]
public String ContactEmail { get; set; }
[DataMember]
[DataType(DataType.Text)]
[Column("ContactAddress1")]
public String ContactAddress1 { get; set; }
... More properties
}
public class StorageContract : Contract
{
[DataMember]
[Column("BoatMaxWidth")]
public Decimal? BoatMaxWidth { get; set; }
[DataMember]
[ColumnAttribute("WidthUOM")]
[DataType(DataType.Text)]
public String WidthUOM { get; set; }
[DataMember]
[Column("LaunchDate")]
[DataType(DataType.Date)]
public DateTime? LaunchDate { get; set; }
[DataMember]
[Column("TotalCharge")]
public Decimal? TotalCharge { get; set; }
... More properties
}
public class RentalContract : Contract
{
[DataMember]
[Column("BoatMake")]
public String BoatMake { get; set; }
[DataMember]
[Column("BoatYear")]
public Int32? BoatYear { get; set; }
[DataMember]
[Column("BoatBeam")]
public Decimal? BoatBeam { get; set; }
[DataMember]
[Column("BoatType")]
[DataType(DataType.Text)]
public String BoatType { get; set; }
... More properties
}
那么为什么这不起作用...
public List<Contract> lvContractList_GetData()
{
List<Contract> ret = null;
switch (Request.QueryString["type"].ToLower())
{
case "storage":
ret = ContractRepository2.GetAllContracts<StorageContract>().ToList();
break;
case "rental":
ret = ContractRepository2.GetAllContracts<RentalContract>().ToList();
break;
}
}
return ret;
}
StorageContract 和 RentalContract 都派生自 Contract 类,这使得它们也成为 Contract 对象。
为什么我不能这样做?