C#设计模式Demo——MVC

devtools/2025/3/15 9:59:49/

设计模式Demo——MVC

    • 1.View
      • 1.1页面示例
      • 1.2View代码
      • 1.3修改界面以及代码
    • 2.Model
    • 3.Controller
    • 4.数据结构
    • 5枚举类型
    • 6.工具类
      • 6.1缓存信息
      • 6.2扩展类.

文件结构图
在这里插入图片描述

1.View

1.1页面示例

在这里插入图片描述

1.2View代码

using System;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.Controller;
using MVC模式实例.Model;
using MVC模式实例.MyEnum;namespace MVC模式实例.View
{public partial class ViewStudent : Form{private StudentController _controller;public ViewStudent(){InitializeComponent();_controller = new StudentController(this, new StudentModel());EventHandler click = (s, a) => CalculateEventArgs(s);btn_Add.Click += click;btn_Remove.Click += click;btn_RemoveName.Click += click;btn_Updata.Click += click;btn_Query.Click += click;}public bool GetInfo(out object id, out object name, out object age){id = null;name = null;age = null;if (dataGridView1.CurrentCell != null){int index = dataGridView1.CurrentCell.RowIndex;id = dataGridView1.Rows[index].Cells["ID"].Value;name = dataGridView1.Rows[index].Cells["姓名"].Value;age = dataGridView1.Rows[index].Cells["年龄"].Value;return true;}else{MessageBox.Show("请选择数据!");}return false;}private void CalculateEventArgs(object sender){if (sender == btn_Add){_controller.Add();}else if (sender == btn_Remove){_controller.Remove(ERemove.ID);}else if (sender == btn_RemoveName){_controller.Remove(ERemove.Name);}else if (sender == btn_Updata){_controller.Updata();}else if (sender == btn_Query){_controller.Query();}}public void DisplayResult(DataTable table){dataGridView1.DataSource = table;}}}

1.3修改界面以及代码

在这里插入图片描述

using System;
using System.Windows.Forms;
using MVC模式实例.DS;namespace MVC模式实例.View
{public partial class FrmUpdataStudent : Form{public Student Student => new Student(long.Parse(textBox1.Text), textBox2.Text, int.Parse(textBox3.Text));public FrmUpdataStudent(object id, object name, object age){InitializeComponent();textBox1.Text = id.ToString();textBox2.Text = name.ToString();textBox3.Text = age.ToString();textBox1.ReadOnly = true;}private void button1_Click(object sender, EventArgs e){if (int.TryParse(textBox3.Text, out _)){DialogResult = DialogResult.OK;}}}
}

2.Model

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;
using MVC模式实例.MyEnum;namespace MVC模式实例.Model
{public class StudentModel{private List<Student> _studentList = new List<Student>();public void Add(Student student){_studentList.Add(student);}public void RemoveByIndex(int index){Console.WriteLine(CachedDescriptionHelper.GetPropertyDescription<ERemove>(nameof(ERemove.ID)));Console.WriteLine(CachedDescriptionHelper.GetPropertyDescription<ERemove>(nameof(ERemove.Name)));if (index == -1) return;var student = _studentList[index];if (MessageBox.Show($"确认删除信息?" +$"\r\n【{CachedDescriptionHelper.GetPropertyDescription<Student>(nameof(Student.Name))} = {student.Name},年龄 = {student.Age}】", "删除提示", MessageBoxButtons.YesNo) != DialogResult.Yes)return;_studentList.RemoveAt(index);}public void RemoveID(long id){RemoveByIndex(QueryIndexByID(id));}public void Remove(Student student){RemoveByIndex(QueryByNameAge(student.Name, student.Age));}public void Updata(Student oldStu, Student newStu){int index = QueryIndexByID(oldStu.ID);if (index != -1){if (oldStu.Name.Equals(newStu.Name) && oldStu.Age.Equals(newStu.Age)){MessageBox.Show("信息内容未修改,无需修改", "提示");return;}if (MessageBox.Show($"修改" + $"\r\n【姓名 = {oldStu.Name},年龄 = {oldStu.Age}】" +$"的信息为:" + $"\r\n【姓名 = {newStu.Name},年龄 = {newStu.Age}】" +$"", "修改提示", MessageBoxButtons.YesNo) != DialogResult.Yes){return;}_studentList[index].Name = newStu.Name;_studentList[index].Age = newStu.Age;}}public Student QueryByID(long id){var index = QueryIndexByID(id);return index != -1 ? _studentList[index].DeepCopy() : null;}public int QueryIndexByID(long id){for (int i = 0; i < _studentList.Count; i++){if (_studentList[i].ID == id)return i;}return -1;}public int QueryByNameAge(string name, int age){for (int i = 0; i < _studentList.Count; i++){var t = _studentList[i];if (t.Name == name && t.Age == age)return i;}return -1;}public DataTable Query(){DataTable dt = new DataTable();dt.Columns.Add("ID");dt.Columns.Add("姓名");dt.Columns.Add("年龄");foreach (var t in _studentList){dt.Rows.Add(t.ID, t.Name, t.Age);}return dt;}}
}

3.Controller

using System;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;
using MVC模式实例.Model;
using MVC模式实例.MyEnum;
using MVC模式实例.View;namespace MVC模式实例.Controller
{public class StudentController{private readonly ViewStudent _view;private readonly StudentModel _model;public StudentController(ViewStudent view, StudentModel model){_view = view;_model = model;}public void Add(){Random ran = new Random();var id = MyExtension.GetTimeLong();var name = ran.Next(100, 999).ToString();int age = ran.Next(18, 30);_model.Add(new Student(id, name, age));_view.DisplayResult(_model.Query());}public void Remove(ERemove type){var ret = _view.GetInfo(out var id, out var name, out var age);if (!ret) return;if (type == ERemove.ID){_model.RemoveID(long.Parse(id.ToString()));_view.DisplayResult(_model.Query());}else{int.TryParse(age.ToString(), out var nAge);Student student = new Student(-1, name.ToString(), nAge);_model.Remove(student);_view.DisplayResult(_model.Query());}}public void Updata(){var ret1 = _view.GetInfo(out var id, out var name, out var age);if (!ret1) return;FrmUpdataStudent dialog = new FrmUpdataStudent(id, name, age);var ret = dialog.ShowDialog();if (ret == DialogResult.OK){Student oldStu = new Student(long.Parse(id.ToString()), name.ToString(), int.Parse(age.ToString()));Student newStu = dialog.Student;_model.Updata(oldStu, newStu);_view.DisplayResult(_model.Query());}}public void Query(){_view.DisplayResult(_model.Query());}}
}

4.数据结构

using System.ComponentModel;namespace MVC模式实例.DS
{public class Student{[Description("学生的唯一标识符")]public long ID { get; set; }[Description("姓名")]public string Name { get; set; }[Description("年龄")]public int Age { get; set; }public Student(long id, string name, int age){ID = id;Name = name;Age = age;}}
}

5枚举类型

using System.ComponentModel;namespace MVC模式实例.MyEnum
{/// <summary>/// 删除操作/// </summary>public enum ERemove{[Description("通过ID删除")]ID,[Description("通过姓名删除")]Name}
}

6.工具类

6.1缓存信息

存储枚举、类属性成员的描述信息

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;namespace MVC模式实例.Extension
{public static class CachedDescriptionHelper{private static readonly Dictionary<string, string> descriptionCache = new Dictionary<string, string>();public static string GetPropertyDescription<T>(string propertyName){string cacheKey = $"{typeof(T).FullName}.{propertyName}";if (descriptionCache.TryGetValue(cacheKey, out string description)){return description;}Type type = typeof(T);PropertyInfo property = type.GetProperty(propertyName);if (property != null){DescriptionAttribute descriptionAttribute = property.GetCustomAttribute<DescriptionAttribute>();if (descriptionAttribute != null){description = descriptionAttribute.Description;descriptionCache[cacheKey] = description;return description;}}FieldInfo field = type.GetField(propertyName);if (field != null){DescriptionAttribute descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>();if (descriptionAttribute != null){description = descriptionAttribute.Description;descriptionCache[cacheKey] = description;return description;}}return null;}}
}

6.2扩展类.

用于深度拷贝、获取时间戳。

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;namespace MVC模式实例.Extension
{/// <summary>/// 扩展类/// </summary>public static class MyExtension{/// <summary>/// 深度拷贝/// </summary>public static T DeepCopy<T>(this T obj){if (!obj.GetType().IsSerializable){return default(T);}using (MemoryStream ms = new MemoryStream()){BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(ms, obj);ms.Position = 0;return (T)formatter.Deserialize(ms);}}/// <summary>/// 获取时间戳/// </summary>/// <returns></returns>public static long GetTimeLong(){long unixTimestampMs = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;return unixTimestampMs;}}
}

http://www.ppmy.cn/devtools/167264.html

相关文章

词向量:优维大模型语义理解的深度引擎

★ 放闸溯源 优维大模型「骨架级」技术干货 第二篇 ⇓ 词向量是Transformer突破传统NLP技术瓶颈的核心&#xff0c;它通过稠密向量空间映射&#xff0c;将离散符号转化为连续语义表示。优维大模型基于词向量技术&#xff0c;构建了运维领域的“语义地图”&#xff0c;实现从…

便捷开启 PDF 功能之旅,绿色软件随心用

软件介绍 以往给大家推荐 DC 时&#xff0c;多是安装版本&#xff0c;这次可不一样&#xff0c;带来的是 DC 绿色版本&#xff0c;无需繁琐安装步骤&#xff0c;只需双击 exe 文件&#xff0c;就能快速打开软件&#xff0c;开启便捷的 PDF 处理之旅。 DC 这款软件功能极其丰富…

边缘计算(Edge Computing)

边缘计算&#xff08;Edge Computing&#xff09;是一种分布式计算范式&#xff0c;它将数据处理和存储功能从传统的集中式云端转移到靠近数据源的网络边缘设备&#xff08;如路由器、网关、本地服务器或终端设备&#xff09;。边缘计算的目标是减少数据传输延迟、降低带宽压力…

Redis项目_黑马点评

部署: 1. 导入sql 开发: Session登录: session的原理是cookie,每个session都有个唯一的sessionId, 在每次访问tomcat的时候sessionId就会自动的写在cookie当中, 携带着sessionId就能找到session, 所以不需要返回用户凭证 每一个进入tomcat的请求都是有一个独立的线程来处理…

Machine Learning中的模型选择

选择适合的机器学习模型是构建高效、准确模型的关键步骤。以下是决定选用哪个模型的主要考虑因素和步骤&#xff1a; 1. 明确问题类型 首先&#xff0c;明确你要解决的问题类型&#xff1a; 分类问题&#xff1a;预测离散类别&#xff08;如垃圾邮件分类、图像识别&#xff09…

【C++项目】从零实现RPC框架「二」:项⽬设计

🌈 个人主页:Zfox_ 🔥 系列专栏:C++从入门到精通 目录 一:🚀 理解项⽬功能二:🔥 框架设计 🦋 服务端模块划分🎀 `Network`🎀 `Protocol`🎀 `Dispatcher`🎀 `RpcRouter`🎀 `Publish-Subscribe`🎀 `Registry-Discovery`🎀 `Server`🦋 客⼾端模块划…

YOLOv11融合[CVPR2025]ARConv中的自适应矩阵卷积

YOLOv11v10v8使用教程&#xff1a; YOLOv11入门到入土使用教程 YOLOv11改进汇总贴&#xff1a;YOLOv11及自研模型更新汇总 《Adaptive Rectangular Convolution for Remote Sensing Pansharpening》 一、 模块介绍 论文链接&#xff1a;https://arxiv.org/pdf/2503.00467 代…

基于SpringBoot实现旅游酒店平台功能十一

一、前言介绍&#xff1a; 1.1 项目摘要 随着社会的快速发展和人民生活水平的不断提高&#xff0c;旅游已经成为人们休闲娱乐的重要方式之一。人们越来越注重生活的品质和精神文化的追求&#xff0c;旅游需求呈现出爆发式增长。这种增长不仅体现在旅游人数的增加上&#xff0…