我正在开发计算并在表格中显示不同报告的软件.但表的结构没有太大差异,许多列是相同的.我首先为每个报告创建了一个类,例如:
class Student()
{
int Class {get; set;}
int Name {get; set;}
int Age {get; set;}
}
class Employee()
{
int Name {get; set;}
int Age {get; set;}
int Salary{get; set;}
}
... and more similar classes
Run Code Online (Sandbox Code Playgroud)
但是在创建了一些类之后我意识到,它们中的许多都有共同的属性,我可以创建公共类:
class HumanReport()
{
int Class {get; set;}//doesn't exist for Employee(null)
int Name {get; set;}
int Age {get; set;}
int Salary{get; set;}// doesn't exist for Student
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,许多属性将包含NULL.哪种方式更适合面向对象的编程?
您应该使用公共字段创建一个基类,然后将其扩展为专用字段
class Human
{
int Name {get; set;}
int Age {get; set;}
}
class Employee : Human
{
int Salary{get; set;}
}
class Student : Human
{
int Class {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这称为继承,是OOP的一个关键特性.
以下是有关继承概念的MSDN文档.