MVC学习九:MVC 特性本质

一、特性的本质就是:对属性、方法、类加特性,本质就是new 一个特性类对象赋值给属性、方法、类。

可以通过反射的方式取得特性的值,代码如下:

①自定义特性

    public class MyAttribute:Attribute
    {
        public string Name { get; set; }
    }

②实体类中使用自定义特性

   public class AttributeTest
    {
        [MyAttribute(Name = "姓名")]
        public string Name { get; set; }
    }

③使用反射显示自定义特性

Type t = typeof(AttributeTest【使用特性的类】);
foreach (PropertyInfo propInfo in t.GetProperties())
{
    //这个.GetCustomAttribute是取得具体的特性,当然也有获取全部特性的方法.GetCustomAttributes
    Attribute propAttribute = propInfo.GetCustomAttribute(typeof(MyAttribute【自定义特性类】), true);
    string strName = ((MyAttribute)propAttribute).Name;//结果就是“姓名”显示出来
}

反射基础知识

http://www.cnblogs.com/WarBlog/p/7346604.html

原文地址:https://www.cnblogs.com/WarBlog/p/7346934.html