OOP之C#设计及其UML(反向工程)
现在总结一下C#类关键字(virtual、abstract、override、new、sealed)的使用(以C#代码体现),并再次熟悉一下OOP思想,使用UML工具EA(Enterprise Architect 7.5)建立其反向工程,生成其UML。
abstract声明抽象类、抽象方法:
- 抽象方法所在类必须为抽象类;
- 抽象类不能直接实例化,必须由其派生类实现;
- 抽象方法不包含方法主体,必须由派生类以override方式实现此方法;
virtual标记方法为虚方法:
- 可在派生类中以override覆盖此方法
- 不覆盖也可由对象调用
- 无此标记的方法(也无其他标记),重写时需用new隐藏原方法
abstract 与 virtual : 方法重写时都使用 override 关键字,interface中的方法和abstract方法都要求实现
sealed关键字:
- 当对一个类应用 sealed 修饰符时,此修饰符会阻止其他类从该类继承,类似于Java中final关键字;
下面为具体的C#代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UserNameSpace { /// <summary> /// 枚举Sex /// </summary> public enum Sex { Male = ‘男‘, Female = ‘女‘ } /// <summary> /// 结构体StudentParams /// </summary> public struct StudentParams { public int id; public string name; public Sex sex; public string grade; public string major; } /// <summary> /// 接口 /// </summary> interface IPeople { string Name { get; set; } Sex Sex { get; set; } short Age { get; set; } void Eat(); } interface ITeacher : IPeople { void Teach(); } interface IStudent : IPeople { void Study(); } /// <summary> /// 抽象基类 /// </summary> abstract class People : IPeople { private string name; private Sex sex; private short age; public string Name { get { return name != null ? name : "NA"; } set { if (value != "") { name = value; } } } public Sex Sex { get { return sex; } set { value = sex; } } public short Age { get { return age > 0 ? age : (short)0; } set { if (value >= 0) { age = value; } } } /// <summary> /// 虚方法 /// </summary> public virtual void Eat() { Console.WriteLine("People eat."); } /// <summary> /// 抽象方法,必须被派生类覆写,则People为抽象类 /// </summary> public abstract void Sleep(); } class Teacher : People, ITeacher { /// <summary> /// 重写基类虚方法 /// </summary> public override void Eat() { Console.WriteLine("Teacher eat."); } /// <summary> /// 重写基类抽象方法 /// </summary> public override void Sleep() { Console.WriteLine("Teacher sleep."); } public void Teach() { Console.WriteLine("Teacher teach."); } } sealed class Master : Teacher { protected void Manage() { } } class Student : People, IStudent { StudentParams param; /// <summary> /// 重写基类虚方法 /// </summary> public override void Eat() { Console.WriteLine("Student eat."); } /// <summary> /// 重写基类抽象方法 /// </summary> public override void Sleep() { Console.WriteLine("Student sleep."); } public void Study() { Console.WriteLine("Student study."); } } class Program { static void Main(string[] args) { Teacher teacher = new Teacher(); ITeacher itea = (ITeacher)teacher; itea.Eat(); Student stu = new Student(); IStudent istu = (IStudent)stu; istu.Eat(); Console.ReadKey(); } } }
我根据上面的代码,利用UML工具EA反向生成了“类图”,如下所示:
时间: 2024-10-13 06:29:10