文章詳情頁
C#抽象類的用法介紹
瀏覽:178日期:2022-06-08 13:37:26
假設有2個類,一個類是主力球員,一個類是替補球員。
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;
}
}
我們發現,NormalPlayer和SubPlayer有共同的屬性和方法,當然也有不同的屬性和方法。把2個類的共同部分抽象出一個基類。
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個類派生于這個基類。
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;
}
}
接著,我們發現NormalPlayer和SubPlayer計算日薪和周薪的方法也可以抽象出來,作為虛方法放到基類中。
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個派生類中,需要重寫基類的虛方法。
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;
}
}
但在實際情況中,BasePlayer只是一個抽象出來的類,我們并不希望實例化這個類。這時候,就可以把BasePlayer設計為abstract抽象類。同時,在抽象類中,提供一個計算薪水的抽象方法。一旦在基類中聲明了沒有方法體的抽象方法,所有派生于這個抽象類的類必須實現或重寫基類中的抽象方法。
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();
}
由此可見,當2個或多個類中有重復部分的時候,我們可以抽象出來一個基類,如果希望這個基類不能被實例化,就可以把這個基類設計成抽象類。
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關內容請查看下面相關鏈接
標簽:
ASP.NET
相關文章:
排行榜

網公網安備