- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力了解 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
对象成为 PrivateLease
或 BusinessLease
对象的通用对象,它保存一个对象的所有数据的对象。然后在插入/更新/删除数据库时,我会先询问哪种类型,以确定将数据插入到哪些表中。
我有一种奇怪的感觉,上面的方法不是解决这个问题的正确方法。有人对此有任何提示吗? :-) 我在谷歌上搜索并阅读了我的编程书籍,每个人都建议这种方法有一个基类,然后从它继承到其他类。
非常感谢任何帮助/提示!
提前致谢。
编辑
本应从一开始就对此进行详细说明,对此我深表歉意!
上述类只是保存来 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; }
}
等..
PrivateLease
和 BusinessLease
类是不同的,因为现实世界中存在不同的租赁变量:-)
基本上我可以只使用两个单独的 PrivateLease
和 BusinessLease
对象,但是由于模型规定 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/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!