标签:
现在总结一下C#类关键字(virtual、abstract、override、new、sealed)的使用(以C#代码体现),并再次熟悉一下OOP思想,使用UML工具EA(Enterprise Architect 7.5)建立其反向工程,生成其UML。
abstract声明抽象类、抽象方法:
virtual标记方法为虚方法:
abstract 与 virtual : 方法重写时都使用 override 关键字,interface中的方法和abstract方法都要求实现
sealed关键字:
下面为具体的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反向生成了“类图”,如下所示:
标签:
原文地址:http://www.cnblogs.com/Leo_wl/p/4989881.html