C#抽象類的用法介紹
假設(shè)有2個(gè)類,一個(gè)類是主力球員,一個(gè)類是替補(bǔ)球員。
public class NormalPlayer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public decimal WeekSalary { get; set; } public string GetFullName() { return this.FirstName + " " + this.LastName; } public decimal GetDaySalary() { return WeekSalary/7; } } public class SubPlayer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public decimal MonthSalary { get; set; } public string GetFullName() { return this.FirstName + " " + this.LastName; } public decimal GetWeekSalary() { return MonthSalary/4; } }
我們發(fā)現(xiàn),NormalPlayer和SubPlayer有共同的屬性和方法,當(dāng)然也有不同的屬性和方法。把2個(gè)類的共同部分抽象出一個(gè)基類。
public class BasePlayer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return this.FirstName + " " + this.LastName; } }
然后讓先前的2個(gè)類派生于這個(gè)基類。
public class NormalPlayer: BasePlayer { public decimal WeekSalary { get; set; } public decimal GetDaySalary() { return WeekSalary/7; } } public class SubPlayer : BasePlayer { public decimal MonthSalary { get; set; } public decimal GetWeekSalary() { return MonthSalary/4; } }
接著,我們發(fā)現(xiàn)NormalPlayer和SubPlayer計(jì)算日薪和周薪的方法也可以抽象出來,作為虛方法放到基類中。
public class BasePlayer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return this.FirstName + " " + this.LastName; } public virtual decimal GetSalary() { throw new NotImplementedException(); } }
在NormalPlayer和SubPlayer這2個(gè)派生類中,需要重寫基類的虛方法。
public class NormalPlayer: BasePlayer { public decimal WeekSalary { get; set; } //獲取日薪 public override decimal GetSalary() { return WeekSalary / 7; } } public class SubPlayer : BasePlayer { public decimal MonthSalary { get; set; } //獲取周薪 public override decimal GetSalary() { return MonthSalary / 4; } }
但在實(shí)際情況中,BasePlayer只是一個(gè)抽象出來的類,我們并不希望實(shí)例化這個(gè)類。這時(shí)候,就可以把BasePlayer設(shè)計(jì)為abstract抽象類。同時(shí),在抽象類中,提供一個(gè)計(jì)算薪水的抽象方法。一旦在基類中聲明了沒有方法體的抽象方法,所有派生于這個(gè)抽象類的類必須實(shí)現(xiàn)或重寫基類中的抽象方法。
public abstract class BasePlayer { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return this.FirstName + " " + this.LastName; } public abstract decimal GetSalary(); }
由此可見,當(dāng)2個(gè)或多個(gè)類中有重復(fù)部分的時(shí)候,我們可以抽象出來一個(gè)基類,如果希望這個(gè)基類不能被實(shí)例化,就可以把這個(gè)基類設(shè)計(jì)成抽象類。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章:
