MVC 基础

 1 //  MVC
 2 //  Model : 代表一个存取数据的对象。可以带有逻辑,在数据变化时,更新控制器。
 3 //  View :  显示模型数据
 4 //  Controller : 作用在模型与视图上。 控制数据流向模型对象,并在数据变化时更新视图。
 5 //  step1: 创建模型  Student.cs
 6 public class Student
 7 {
 8     private string rollNo;
 9     private string name;
10 
11     public string RollNo
12     {
13         get => return rollNo;
14         set => rollNo = value;
15     }
16 
17     public string Name
18     {
19         get => return name;
20         set => name = value;
21     }
22 }
23 
24 // step2 : 创建视图 studentView.cs
25 public class StudentView
26 {
27     public void printStudentDetails(string studentName, string studentRollNo)
28     {
29         console.writeline("Student: ");
30     }
31 }
32 
33 // step3 : 创建控制器 StudentController.cs
34 // 控制器 : 将模型类 与 视图类 当成 成员
35 // 控制数据流向模型对象
36 // 在控制其中 必须有两个函数 (1): 更改模型数据的函数 (2) 更新视图的函数
37 public class StudentController
38 {
39     private Student model;
40     private StudentView view;
41 
42     public StudentController(Student model, Student view)
43     {
44         this.model = model;
45         this.view = view;
46     }
47 
48     public void setStudentPara(string name, string rollNo)
49     {
50         model.Name = name;
51         model.RollNo = rollNo;
52     }
53 
54     public void updateView()
55     {
56         view.printStudentDetails(model.Name, model.RollNo);
57     }
58 }
59 
60 // step4 : 使用 studentController 方法演示 MVC 设计模式的用法
61 public class MVCPatternDemo
62 {
63     public static void Main(string[] args)
64     {
65         // 获取学生数据
66         Student model = retriveStudentFromDataBase();
67 
68         // 创建视图
69         StudentView view = new StudentView();
70 
71         // 将学生信息输出到控制台,并更新信息
72         StudentController controller = new StudentController(model, view);
73         controller.updateView();
74 
75         // 更新模型数据
76         controller.setStudentPara("Damon", "101335")
77         controller.updateView();
78 
79     }
80 
81     private static Student retriveStudentFromdataBase()
82     {
83         Student student = new Student();
84         student.Name = "Damon";
85         student.RollNo = "101334";
86         return student;
87     }
88 }
原文地址:https://www.cnblogs.com/yaolin1228/p/8289137.html