学生类:
/// <summary> /// 学生实体 /// </summary> public class Student { public int Id { get; set; } public int ClassId { get; set; } public string Name { get; set; } public int Age { get; set; } public void Study() { Console.WriteLine("{0} {1}跟着Richard老师学习.net高级开发", this.Id, this.Name); } public void StudyHard() { Console.WriteLine("{0} {1}跟着Richard老师努力学习.net高级开发", this.Id, this.Name); } }
调用:
Student student = new Student() { Id = 1, Name = "Mr.zhang", Age = 25, ClassId = 2 }; student.Study();
之后如果在学生类再加一个方法,正常的情况下是直接在学生类中做修改,但是如果为了遵循开闭原则的话可以做一个扩展方法:
public static class ExtendMethod { /// <summary> /// 扩展方法:添加一个第三方静态类,把当前需要扩展的类作为参数添加方法,在第一个参数前加一个this /// </summary> /// <param name="student"></param> public static void StudyPractise(this Student student) { Console.WriteLine("{0} {1}跟着Richard老师学习基础班!", student.Id, student.Name); } }
调用:
student.StudyPractise(); //扩展方法;看起来跟实例方法调用方式一样