gpt4 book ai didi

c# - 多态性:做对

转载 作者:行者123 更新时间:2023-11-30 20:06:13 25 4
gpt4 key购买 nike

我正在努力了解 C# 中的多态性/继承情况。

我现在拥有的是这些类:

Lease (the base class containing the general data)
PrivateLease (inheriting from the Lease class)
BusinessLease (inheriting from the Lease class)

我想实现的是:

Lease lease = new PrivateLease();

这目前有效,但执行此操作时我无法访问 PrivateLease 对象上的属性。至少在不首先将 Lease 对象转换为 PrivateLease 对象的情况下。

我希望 Lease 对象成为 PrivateLeaseBusinessLease 对象的通用对象,它保存一个对象的所有数据的对象。然后在插入/更新/删除数据库时,我会先询问哪种类型,以确定将数据插入到哪些表中。

我有一种奇怪的感觉,上面的方法不是解决这个问题的正确方法。有人对此有任何提示吗? :-) 我在谷歌上搜索并阅读了我的编程书籍,每个人都建议这种方法有一个基类,然后从它继承到其他类。

非常感谢任何帮助/提示!

提前致谢。

编辑

本应从一开始就对此进行详细说明,对此我深表歉意!

上述类只是保存来 self 的 ASP.NET 解决方案的 UI 的数据,以通过数据访问层对数据库执行 CRUD 操作。所以基本上这些类只包含一堆属性来保存数据。即:

public class Lease
{
public int Id { get; set; }
public bool IsActive { get; set; }
public string TypeOfRental { get; set; }
public string RentalPeriod { get; set; }
public DateTime TakeoverDate { get; set; }
}

public class PrivateLease : Lease
{
public string Floor { get; set; }
public string Side { get; set; }
public int FloorSize { get; set; }
public int NumberOfRooms { get; set; }
}

等..

PrivateLeaseBusinessLease 类是不同的,因为现实世界中存在不同的租赁变量:-)

基本上我可以只使用两个单独的 PrivateLeaseBusinessLease 对象,但是由于模型规定 Address 对象可以容纳一个或更多 Lease,这不是一个选项。

对我来说,我似乎要在 ASP.NET 前端和 DAL 上经历一次重大的类型转换 hell ? :-/

最佳答案

不要在消费者层决定(选择逻辑),而让类自己决定:

// or you ILease interface if a parent class will not contain any shared logic
abstract class Lease
{
public abstract void Do();

// example of shared logic
protected void Save(Lease l) { }
}

class PrivateLease : Lease
{
public override void Do() { // private logic here }
}

class BusinessLease : Lease
{
public override void Do() { // business logic here }
}

用法:

Lease l = ...
l.Do(); // execute the logic

您可能想要创建一个用于创建对象的工厂:

static class LeaseFactory<T> where T : Lease, new() // constraint to require default constructor existence
{
public static Leas Create()
{
return new T();
}
}

关于c# - 多态性:做对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com