在子类db-table中存储基本抽象类属性

时间:2014-08-31 19:35:58

标签: c# database class inheritance abstract

我在从抽象类中存储属性时遇到一些问题,构造函数似乎工作得很好。但是我无法将基本属性存储在子类数据库表中。

public abstract class Vehicle : IComparable< Vehicle >, IComparable {
    public Int16 VehicleID;
    public DateTime ProductionDate;

    public Vehicle(Int16 _ Vehicle ID,DateTime _ProductionDate)
    {
        this.AccidentID = _ AccidentID;
        this.ProductionDate = _ProductionDate;
    }

    int IComparable.CompareTo(object other) {
        return CompareTo((Vehicle)other);
    }
    public int CompareTo(Vehicle other){
        return this.ProductionDate.CompareTo(other.ProductionDate);
    }

    public Vehicle()
    {}
}

public class Car : Vehicle
{
    public Car ()
    {
    }

    public Car (Int16 _VehicleID,DateTime _ProductionDate, Int16 _CarAttribute1, Int16 _CarAttribute2):base(_Vehicle ID,_ProductionDate)
    {
        this.AccidentID = _ AccidentID;
        this.ProductionDate = _ProductionDate;
        this.CarAttribute1 = _CarAttribute1
        this.CarAttribute2 = _CarAttribute2

    }

    [PrimaryKey, AutoIncrement, Column("Attribute1")]
    public Int16 CarAttribute1{ get; set;}
    [Column("Attribute2")]
    public Int16 CarAttribute2{ get; set;}
}

我对C#很陌生,所以一些指导意见得到赞赏:)我错过了什么?

1 个答案:

答案 0 :(得分:0)

在基类中,您应该使用属性而不是字段,因此请调整基类,如下所示:

public abstract class Vehicle : IComparable<Vehicle>, IComparable {

public Int16 AccidentID { get; set; }
public DateTime ProductionDate { get; set;}

public Vehicle(Int16 _ Vehicle ID,DateTime _ProductionDate)
{
    this.AccidentID = _ AccidentID;
    this.ProductionDate = _ProductionDate;
}

int IComparable.CompareTo(object other) {
    return CompareTo((Vehicle)other);
}
public int CompareTo(Vehicle other){
    return this.ProductionDate.CompareTo(other.ProductionDate);
}

public Vehicle()
{}

}

所以我改变了:

public Int16 VehicleID;
public DateTime ProductionDate;

为:

public Int16 AccidentID { get; set; }
public DateTime ProductionDate { get; set;}

BTW:您在基类中有VehicleID字段,但在构造函数中,您将值设置为AccidentID而不是VehicleID。我认为这只是描述中的一个错字,对吧?所以我使用 AccidentID 作为属性名称,所以请检查它是否正确。