【问题标题】:Storing base abstract class attributes in subclass db-table在子类 db-table 中存储基本抽象类属性
【发布时间】:2014-08-31 19:35:58
【问题描述】:

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

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.您使用哪个框架来处理 DB? 2. 你的代码有什么问题?数据库中的异常、错误或 NULL 数据?
  • 嗨,我正在使用单声道和 Xamarin IDE,其中我使用了一个名为 SQLite.net async (nuget.org/packages/SQLite.Net.Async-PCL) 的组件,我的数据库列中的基类属性为空。

标签: c# database class inheritance abstract


【解决方案1】:

在基类中你应该使用属性而不是字段,所以像这样调整你的基类:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2018-09-17
    • 2018-07-26
    • 1970-01-01
    • 2019-06-23
    • 2018-02-06
    • 2018-10-21
    相关资源
    最近更新 更多