簡體   English   中英

如何在不重新編碼的情況下更改類?

[英]How to change a class without re-coding?

我正在我的項目中創建一個駕駛執照對象,員工都將擁有一個與他們唯一的時鍾編號相關聯的駕駛執照對象。 我的數據庫中有一個單獨的表用於駕駛執照,但將來需要添加更多類型的車輛,是否可以在不重新編碼的情況下執行此操作? 我的數據庫中的列與下面類的屬性相同

public class LicenseDTO
{
    public int ClockNo { get; set; }
    public bool CBalance { get; set; }
    public bool MR16 { get; set; }
    public bool OrderPicker { get; set; }
    public bool Reach { get; set; }
    public bool Pedestrian { get; set; }
    public bool Lorry { get; set; }
    public bool Sweeper { get; set; }
    public bool Washer { get; set; }
}

編輯

我試圖盡我所能創造這個,但我覺得它真的很啰嗦,可以用更有效的方式來完成。 這是我的代碼的更新版本。

public class LicenseDTO
{
    public int ClockNo { get; set; }
    public List<Common.VehicleTypeDTO> Vehicles { get; set; }
}

public class VehicleTypeDTO
{
    public string VehicleType { get; set; }
    public bool Allowed { get; set; }
}

private void btnClockCardIn_Click(object sender, EventArgs e)
    {
        Common.LicenseDTO License = new Common.LicenseDTO();
        List<Common.VehicleTypeDTO> Vehicles = new List<Common.VehicleTypeDTO>();
        Common.VehicleTypeDTO CBalance = new Common.VehicleTypeDTO();
        Common.VehicleTypeDTO MR16 = new Common.VehicleTypeDTO();
        License.Vehicles = Vehicles;
        CBalance.VehicleType = "CBalance";
        CBalance.Allowed = true;
        MR16.VehicleType = "MR16";
        MR16.Allowed = false;
        License.Vehicles.Add(CBalance);
        License.Vehicles.Add(MR16);
        foreach (Common.VehicleTypeDTO Vehicle in License.Vehicles)
        {
            MessageBox.Show(Vehicle.VehicleType + " " + Vehicle.Allowed);
        }
    }

為什么不創建一個包含車輛類型的表格? 將來您可以訪問您的表並插入更多類型。

public class VehicleTypeDTO
{
    public int Id{ get; set; }
    public string Name{ get; set; }
}

public class LicenseDTO
{
    public int Id { get; set; }
    public List<VehicleTypeDTO> VehicleTypes { get; set; }
}

您應該在類型為 Vehicle 的數組旁邊創建了一個具有 ClockNo 和 CBalance 屬性的實體 LicenseDTO。 這將是一個界面。 接口 Vehicle 可以定義車輛具有的任何通用方法。 並且所有未來的車輛都必須實現該接口。 這樣您就不必更改任何代碼。 未經編輯,您當前的代碼無法“更改”。 您可以嘗試使用另一個實現上述接口的實體類來擴展您的 LicenseDTO 類。 但沒有更多你可以不編輯。

如果您想要可維護性,請從接口、存儲庫模式、抽象類和依賴注入開始。

不要在數據庫中使用多個位列來指示不同類型的車輛,而是使用單個VehicleType表。 然后,您可以根據需要添加任意數量的不同車輛類型,並使用 VehicleTypeID 來唯一標識它們。 然后,您可以將越來越多的車輛類型添加到表中,而無需編寫更多代碼。

VehicleType
    VehicleTypeID int
    VehicleTypeName varchar(50)

public class LicenseDTO
{
    public int ClockNo { get; set; }
    public int VehicleTypeID { get; set; }
}

如果您想針對單個 ClockNo 擁有多種類型的車輛,請使用 int 列表:

public class LicenseDTO
{
    public int ClockNo { get; set; }
    public List<int> VehicleTypes { get; set; }
}

或者,您可以引用 VehicleType 對象,而不僅僅是 ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM