C#设计模式Demo——MVC

news2025/3/20 4:23:19

设计模式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模式实例.DS;
using MVC模式实例.Model;
using MVC模式实例.MyEnum;

namespace MVC模式实例.View
{
    public partial class ViewStudent : Form
    {
        public event EventHandler<EventArgsStudent> EventManage;

        public ViewStudent()
        {
            InitializeComponent();
            _ = new StudentController(this, new StudentModel());
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            EventArgsStudent instance = new EventArgsStudent(EOperation.Add);
            EventManage?.Invoke(this, instance);
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            EventManage?.Invoke(this, new EventArgsStudent(EOperation.Query));
        }

        private void btn_Updata_Click(object sender, EventArgs e)
        {
            EventManage?.Invoke(this, CurArgsStudent(EOperation.Updata));
        }

        private void btn_RemoveName_Click(object sender, EventArgs e)
        {
            EventManage?.Invoke(this, CurArgsStudent(EOperation.Remove_Nama));
        }

        private void btn_Remove_Click(object sender, EventArgs e)
        {
            EventManage?.Invoke(this, CurArgsStudent(EOperation.Remove_Id));
        }


        private EventArgsStudent CurArgsStudent(EOperation type)
        {
            EventArgsStudent eventArgsStudent = new EventArgsStudent(type);
            if (dataGridView1.CurrentCell != null)
            {
                int index = dataGridView1.CurrentCell.RowIndex;
                Student.GetPropertyName(out string titleId, out string titleName, out string titleAge);
                var id = long.Parse(dataGridView1.Rows[index].Cells[titleId].Value.ToString());
                var name = dataGridView1.Rows[index].Cells[titleName].Value.ToString();
                var age = int.Parse(dataGridView1.Rows[index].Cells[titleAge].Value.ToString());
                eventArgsStudent = new EventArgsStudent(type, new Student(id, name, age));
            }
            else
            {
                MessageBox.Show("请选择数据!");
            }

            return eventArgsStudent;
        }

        public void DisplayResult(DataTable table)
        {
            dataGridView1.DataSource = table;
        }

    }

    public class EventArgsStudent : EventArgs
    {
        public EOperation Type { get; set; }
        public Student Student { get; set; }

        public EventArgsStudent(EOperation type, Student student)
        {
            Type = type;
            Student = student;
        }

        public EventArgsStudent(EOperation type)
        {
            Type = type;
        }
    }

}

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();
            Student.GetPropertyName(out string titleId, out string titleName, out string titleAge);
            label1.Text = titleId;
            label2.Text = titleName;
            label3.Text = titleAge;
            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.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using MVC模式实例.DS;
using MVC模式实例.Extension;


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)
        {
            if (index == -1) return;
            var student = _studentList[index];
            Student.GetPropertyName(out string id, out string name, out string age);

            if (MessageBox.Show($"确认删除信息?" +
                                $"\r\n【{name} = {student.Name}{age} = {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;
                }

                Student.GetPropertyName(out string id, out string name, out string age);

                if (MessageBox.Show($"修改" + $"\r\n【{name}  = {oldStu.Name}{age}  = {oldStu.Age}】" +
                                    $"的信息为:" + $"\r\n【{name}  = {newStu.Name}{age} = {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()
        {
            Student.GetPropertyName(out string id, out string name, out string age);

            DataTable dt = new DataTable();
            dt.Columns.Add(id);
            dt.Columns.Add(name);
            dt.Columns.Add(age);

            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;
            _view.EventManage += OnEventManage;
        }

        private void OnEventManage(object sender, EventArgsStudent e)
        {
            switch (e.Type)
            {
                case EOperation.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));
                    break;
                case EOperation.Remove_Id:
                    _model.RemoveID(e.Student.ID);
                    break;
                case EOperation.Remove_Nama:
                    _model.Remove(e.Student);
                    break;
                case EOperation.Updata:
                    FrmUpdataStudent dialog = new FrmUpdataStudent(e.Student);
                    var ret = dialog.ShowDialog();
                    if (ret != DialogResult.OK) return;
                    Student oldStu = e.Student;
                    Student newStu = dialog.Student;
                    _model.Updata(oldStu, newStu);
                    break;
                case EOperation.Query:
                    break;
            }
            _view.DisplayResult(_model.Query());
        }

    }
}

4.数据结构

using System.ComponentModel;
using MVC模式实例.Extension;

namespace MVC模式实例.DS
{
    public class Student
    {

        [Description("ID")]
        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;
        }

        public static void GetPropertyName(out string titleId, out string titleName, out string titleAge)
        {
            titleId = GetPropertyName(nameof(ID));
            titleName = GetPropertyName(nameof(Name));
            titleAge = GetPropertyName(nameof(Age));
        }

        public static string GetPropertyName(string propertyName)
        {
            return CachedDescriptionHelper.GetPropertyDescription<Student>(propertyName);
        }

    }
}


5.枚举类型

using System.ComponentModel;


namespace MVC模式实例.MyEnum
{

    /// <summary>
    /// 删除操作
    /// </summary>
    public enum EOperation
    {

        [Description("添加数据")]
        Add,

        [Description("通过ID删除")]
        Remove_Id,

        [Description("通过姓名删除")]
        Remove_Nama,

        [Description("修改数据")]
        Updata,

        [Description("查询数据")]
        Query,

    }
}

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.coloradmin.cn/o/2318129.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【sql靶场】第18-22关-htpp头部注入保姆级教程

目录 【sql靶场】第18-22关-htpp头部注入保姆级教程 1.回顾知识 1.http头部 2.报错注入 2.第十八关 1.尝试 2.爆出数据库名 3.爆出表名 4.爆出字段 5.爆出账号密码 3.第十九关 4.第二十关 5.第二十一关 6.第二十二关 【sql靶场】第18-22关-htpp头部注入保姆级教程…

LabVIEW棉花穴播器排种自动监测系统

一、项目背景与行业痛点 1. 农业需求驱动 我国棉花主产区&#xff0c;种植面积常年超250万公顷&#xff0c;传统人工播种存在两大核心问题&#xff1a; 效率瓶颈&#xff1a;人均日播种面积不足0.5公顷&#xff0c;难以匹配规模化种植需求&#xff1b; 精度缺陷&#xff1a;人…

【程序人生】成功人生架构图(分层模型)

文章目录 ⭐前言⭐一、根基层——价值观与使命⭐二、支柱层——健康与能量⭐三、驱动层——学习与进化⭐四、网络层——关系系统⭐五、目标层——成就与财富⭐六、顶层——意义与传承⭐外层&#xff1a;调节环——平衡与抗风险⭐思维导图 标题详情作者JosieBook头衔CSDN博客专家…

速通大厂测开

最近26届暑期实习招聘和25届春招已经开始&#xff0c;测开学习圈也有同学拿到offer了 今天分享一位25届秋招圈友快速拿到大厂测开offer的经历&#xff0c;希望对大家有所帮助 我是某211本科生&#xff0c;在去年暑假准备考研的间隙意外收获了某大厂测开实习offer&#xff0c;…

基于Netty实现高性能HTTP反向代理

以下将分步骤实现一个基于Netty的高性能HTTP反向代理&#xff0c;支持动态路由、负载均衡和基础鉴权功能。 1. 项目依赖配置&#xff08;Maven&#xff09; 2. 定义路由规则 3. 实现HTTP反向代理服务端 4. 实现反向代理处理器 5. 实现基础鉴权 6. 性能优化策略 连接池管理…

【NLP 37、实践 ⑨ NER 命名实体识别任务 LSTM + CRF 实现】

难过的事情我要反复咀嚼&#xff0c;嚼到它再也不能困扰我半分 —— 25.3.13 数据文件&#xff1a; 通过网盘分享的文件&#xff1a;Ner命名实体识别任务 链接: https://pan.baidu.com/s/1fUiin2um4PCS5i91V9dJFA?pwdyc6u 提取码: yc6u --来自百度网盘超级会员v3的分享 一、配…

再学:函数可见性、特殊函数、修饰符

目录 1.可见性 2.合约特殊函数 constructor && getter 3. receive && fallback 4.view && pure 5.payable 6.自定义函数修饰符 modifier 1.可见性 public&#xff1a;内外部 private&#xff1a;内部 external&#xff1a;外部访问 internal&…

基于Spring Boot的项目申报系统的设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

Web元件库 ElementUI元件库+后台模板页面(支持Axure9、10、11)

Axure是一款非常强大的原型设计工具&#xff0c;它允许设计师和开发者快速创建高保真原型&#xff0c;以展示应用或网站的设计和功能。通过引入各种元件库&#xff0c;如ElementUI元件库&#xff0c;可以极大地丰富Axure的原型设计能力&#xff0c;使其更加贴近实际开发中的UI组…

孜然SEO静态页面生成系统V1.0

孜然SEO静态页面生成系统&#xff0c;1秒生成上万个不同的静态单页系统&#xff0c;支持URL裂变采集&#xff0c;采集的内容不会重复&#xff0c;因为程序系统自带AI重写算法&#xff0c;AI扩写算法&#xff0c;可视化的蜘蛛池系统让您更清楚的获取到信息&#xff01; 可插入二…

Blender-MCP服务源码3-插件开发

Blender-MCP服务源码3-插件开发 Blender-MCP服务源码解读-如何进行Blender插件开发 1-核心知识点 1&#xff09;使用Blender开发框架学习如何进行Blender调试2&#xff09;学习目标1-移除所有的Blender业务-了解如何MCP到底做了什么&#xff1f;3&#xff09;学习目标2-模拟MC…

C语言和C++到底有什么关系?

C 读作“C 加加”&#xff0c;是“C Plus Plus”的简称。 顾名思义&#xff0c;C 就是在 C 语言的基础上增加了新特性&#xff0c;玩出了新花样&#xff0c;所以才说“Plus”&#xff0c;就像 Win11 和 Win10、iPhone 15 和 iPhone 15 Pro 的关系。 C 语言是 1972 年由美国贝…

【华三】路由器交换机忘记登入密码或super密码的重启操作

【华三】路由器交换机忘记登入密码或super密码的重启操作 背景步骤跳过认证设备&#xff1a;路由器重启设备翻译说明具体操作 跳过当前系统配置重启设备具体操作 背景 当console口的密码忘记&#xff0c;或者说本地用户的密码忘记&#xff0c;其实这时候是登入不了路由器的&am…

DeepSeek-prompt指令-当DeepSeek答非所问,应该如何准确的表达我们的诉求?

当DeepSeek答非所问&#xff0c;应该如何准确的表达我们的诉求&#xff1f;不同使用场景如何向DeepSeek发问&#xff1f;是否有指令公式&#xff1f; 目录 1、 扮演专家型指令2、 知识蒸馏型指令3、 颗粒度调节型指令4、 时间轴推演型指令5、 极端测试型6、 逆向思维型指令7、…

HOVER:人形机器人的多功能神经网络全身控制器

编辑&#xff1a;陈萍萍的公主一点人工一点智能 HOVER&#xff1a;人形机器人的多功能神经网络全身控制器HOVER通过策略蒸馏和统一命令空间设计&#xff0c;为人形机器人提供了通用、高效的全身控制框架。https://mp.weixin.qq.com/s/R1cw47I4BOi2UfF_m-KzWg 01 介绍 1.1 摘…

HTML中滚动加载的实现

设置div的overflow属性&#xff0c;可以使得该div具有滚动效果&#xff0c;下面以div中包含的是table来举例。 当table的元素较多&#xff0c;以至于超出div的显示范围的话&#xff0c;观察下该div元素的以下3个属性&#xff1a; clientHeight是div的显示高度&#xff0c;scrol…

Python----计算机视觉处理(Opencv:形态学变换)

一、形态学变化 形态学变换&#xff08;Morphological Transformations&#xff09;是一种基于形状的图像处理技术&#xff0c;主要处理的对象为二值化图像。 形态学变换有两个输入和一个输出&#xff1a;输入为原始图像和核&#xff08;即结构化元素&#xff09;&#xff0c;输…

opencv中stitch图像融合

openv版本: opencv249 vs &#xff1a;2010 qt : 4.85 #include "quanjing.h"#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <open…

matlab R2024b下载教程及安装教程(附安装包)

文章目录 前言一、matlab R2024b安装包下载二、matlab R2024b安装教程 前言 为帮助大家顺利安装该版本软件&#xff0c;特准备matlab R2024b下载教程及安装教程&#xff0c;它将以简洁明了的步骤&#xff0c;指导你轻松完成安装&#xff0c;开启 MATLAB R2024 的强大功能之旅。…

游戏引擎学习第167天

回顾和今天的计划 我们不使用引擎&#xff0c;也不依赖库&#xff0c;只有我们自己和我们的小手指在敲击代码。 今天我们会继续进行一些工作。首先&#xff0c;我们会清理昨天留下的一些问题&#xff0c;这些问题我们当时没有深入探讨。除了这些&#xff0c;我觉得我们在资产…