当前位置: 首页 > news >正文

C#设计模式Demo——MVC

设计模式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;
        }

    }
}

相关文章:

  • matlab中如何集成使用python
  • 文捕---博客文章下载工具
  • AI入门7:python三种API方式调用本地Ollama+DeepSeek
  • bak 文件
  • 深海300米的低温环境中的BMS优化方法
  • STM32---FreeRTOS事件标志组
  • openEuler24.03 LTS下安装MySQL8
  • dfs(十二)21. 合并两个有序链表 递归解决
  • Spring 框架中常用注解和使用方法
  • 如何管理需求变更
  • 做游戏的发展方向
  • Skyeye 云智能制造办公系统 VUE 版本 v3.15.13 发布
  • ChatGPT and Claude国内使用站点
  • CareUEyes护眼软件深度解析:为你的双眼保驾护航
  • 基于Gemini 生成 Gemini Embedding
  • 学习笔记之注册用户如何防止缓存穿透
  • 365天之第P10周:Pytorch实现车牌识别
  • OceanBase 4.3.3 AP 功能解析:物化视图
  • 嵌入式开发之STM32学习笔记day06
  • C语言:编程设计猜数游戏
  • 奥斯卡新规:评委必须看完影片再投票;网友:以前不是啊?
  • “非思”的思想——探索失语者的思想史
  • 经济日报社论:书写新征程上奋斗华章
  • “80后”蒋美华任辽宁阜新市副市长
  • 徐徕任上海浦东新区副区长,此前已任区委常委
  • 人民日报:在大有可为的时代大有作为