随笔 - 17  文章 - 0  评论 - 378  阅读 - 87687

与继承相关的一些重构(二)

5.提取主类:提取一个基类,抽象出共有方法,比较常用的重构,这里的基类也许并不存在,需要自己新建立。

 用法场景:当有一个类中的某个方法需要经常被其他的类调用的时候,说明这个方法重用率很高,可以考虑把它抽象出来,放到一个基类中。

 

复制代码
代码
//重构前
public class Dog
{
public void EatFood()
{
// eat some food
}

public void Groom()
{
// perform grooming
}
}
//重构后
public class Animal
{
public void EatFood()
{
// eat some food
}

public void Groom()
{
// perform grooming
}
}
public class Dog : Animal
{
}
复制代码

 

6.提取子类:将基类中的方法放到子类中,这里的子类也许并不存在,需要自己新建立。

 

 用法场景:当基类中的某些方法并不是面向所有或者大多数类的时候,需要把这些方法下放到子类中。

 

复制代码
代码
//重构前
public class Registration
{
public NonRegistrationAction Action { get; set; }
public decimal RegistrationTotal { get; set; }
public string Notes { get; set; }
public string Description { get; set; }
public DateTime RegistrationDate { get; set; }
}
//重构后
public class Registration
{
public decimal RegistrationTotal { get; set; }
public string Description { get; set; }
public DateTime RegistrationDate { get; set; }
}

public class NonRegistration : Registration
{
public NonRegistrationAction Action { get; set; }
public string Notes { get; set; }
}
复制代码

 

7.合并继承:把子类合并到基类中去。

 

 用法场景:当子类只有属性定义,并且这些属性可以放置在基类中,那这个子类就是多余的,在把属性和基类合并后就可以移除了。

 

复制代码
代码

//重构前
public class Website
{
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<Webpage> Pages { get; set; }
}
public class StudentWebsite : Website
{
public bool IsActive { get; set; }
}
//重构后
public class Website
{
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<Webpage> Pages { get; set; }
public bool IsActive { get; set; }
}
复制代码

 

 

  继承相关的重构就这几点,尝试在项目中多用用,很快就有感觉了:)

posted on   Dennis.Yang  阅读(432)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
< 2010年7月 >
27 28 29 30 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7

点击右上角即可分享
微信分享提示