码迷,mamicode.com
首页 > Web开发 > 详细

仿 MVC 三大特性

时间:2019-05-21 17:21:51      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:img   直接   console   就会   span   传参   OLE   name   efi   

1.先做个小例子

  特性,只能通过反射实现

  我们自定义一个特性

    public class CustomAttribute : Attribute
    {
        public int Id;
        public string Name;
        public string Reamrk;
        public string Desc;
        public CustomAttribute() : this(0, "") { }//如果没传参,使用this给默认值
        public CustomAttribute(int _id, string _name)
        {
            this.Id = _id;
            this.Name = _name;
        }
        public void Show()
        {
            Console.WriteLine($"{Id}_{Name}_{Reamrk}_{Desc}");
        }
    }

  写一个类并注册特性

    [Custom(123,"kxy",Desc ="是个帅哥",Reamrk ="学员")]
    public class Student
    {
        [Custom(124, "wzz", Desc = "是个丑逼", Reamrk = "学员")]
        public void Study()
        {
            Console.WriteLine($"正在学习");
        }
    }

  实现特性调用,只能通过反射,没办法和MVC那样直接调用接口特性就会执行(因为MVC已经封装好了调用的反射机制)

    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            Type type = student.GetType();
            // 判断该类是否注册了CustomAttribute
            if (type.IsDefined(typeof(CustomAttribute), true))
            {
                var attribute = type.GetCustomAttribute<CustomAttribute>();
                attribute.Show();
            }

            MethodInfo method = type.GetMethod("Study");
            // 判断该方法是否注册了CustomAttribute
            if (method.IsDefined(typeof(CustomAttribute), true))
            {
                var attribute = method.GetCustomAttribute<CustomAttribute>();
                attribute.Show();
            }

            // 执行了特性之后执行方法
            student.Study();
            Console.ReadLine();
        }
    }

  结果:技术图片

  由上可知,执行步骤先是执行类注册、在是方法注册的特性,然后再是执行我们需要的方法

  这个思路和MVC 提供的特性是一致的

2.实现特性

仿 MVC 三大特性

标签:img   直接   console   就会   span   传参   OLE   name   efi   

原文地址:https://www.cnblogs.com/wskxy/p/10900962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!