博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.Net 特性 attribute 学习 ----自定义特性
阅读量:7240 次
发布时间:2019-06-29

本文共 2337 字,大约阅读时间需要 7 分钟。

什么是特性?
[Obsolete("不要用无参构造函数",true)] 放在方式上, 该方法就不能使用了
 [Serializable]放在类上面。该类就是可以序列化和反序列化使用了。
 
在命名空间、类、方法、属性、字段、枚举 上用中括号[]
 
自定义特性,特性就是类:必须继承Attribute 或者是Attribute的泛生类
public class SizeAttribute : Attribute       // 这个就是一个自定义特性
{
          public SizeAttribute()
          {
                   Console.WriteLine("这是一个SizeAttribute的构造函数");
           }
 
这个特性就创建好了
在其他类, 如Student类上
[SizeAttribute]        //在类上写特性
public class Student
{
         [SizeAttribute] //在属性上写特性
          public int Id{set; get;}
 
          public string Name{set;get}
 
           [SizeAttribute] //在方法上写特性
           public void Show()
           {
                   Console.WriteLine("Show")
             }
}
 
当然特性 也可以有描述自己特性的办法
就是在特性上面写上
[AttributeUsage(AttributeTargets.All,AllowMultiple =false,Inherited =true)]
public class SizeAttribute : Attribute
{
}
 
//意思是当前特性包含所有类型都可以使用,只能单一使用,可以继承
 
 
特性:
1.当程序编译和执行,特性和注释的效果是一样的,没有任何不同
 
2.特性编译后是metadata,只有在反射的时候,才能使用特性。
 
3.特性可以做权限检测,属性验证,封装枚举等很多功能。
 
4.特性是一个类,可以用作标记元素,编译时生成在metadata里,平时不影响程序的运行,除非主动用反射去查找,
可以得到一些额外的信息和操作,提供了更丰富扩展空间,特性可以在不 破坏类型封装的前提下,额外增加功能。
 
 
例子:有一个学生类,希望用特性,让添加的学生年龄不能小于12岁,大于20岁
 
//学生类
public class Student
{
            public int Id { get; set; }
            public string Name { get; set; }
             public int Age { get; set; }
            [Obsolete("不要用无参构造函数",true)] //这个特性,是不能使用无参构造函数
            public Student()
            { }
            public Student(int id, string name,int age)
           {
            this.Id = id;
            this.Name = name;
 
            [ControlAgeAttribute(_vMin=12,_vMax=30)] //要判断年龄,年龄小于20,大于12, 就将下面自定义的特性放在这个属性上面
            this.Age = age;
            }
            public void Show()
            {
              Console.WriteLine("这个show方法");
             }
}
 
//控制年龄的特性 :特性的命名规范--名称后面为Attribute
public class ControlAgeAttribute : Attribute
{
          public int _vMin{get;set;}//最小年龄 
           public int _vMax{get;set;} //最大年龄        
 
          public bool  CompareAge(int age)
          {
                   return age>_vMin && age <_vMax ? true : false; //
           }
}
 
//反射使用特性---用静态方法
public static class Manage
{
          public static bool CompareAgeManage(this Student stu)
         {
               bool result = false;
               Type type = typeof(stu);//先获取类型
                ProperyInfo prop = type.GetProperty("Age");//反射获取年龄属性
                if (prop.IsDefined(typeof(ControlAgeAttribute ),true))//判断当前属性是否有ControlAgeAttribute 的特性
                {
                      ControlAgeAttribute  attribute = (ControlAgeAttribute) prop.GetCustomAttribute(typeof(ControlAgeAttribute ),true);
                        //获取特性
                      result =  attribute.CompareAge(stu.Age);
                      return result;//得到结果返回
                 }
                 
                        
 
              return result;
         }
}
 
//控制台Main方法里面执行
static void Main(string[] args)
{
Student student = new Student(12,"hahaha",15);
Console.WriteLine(student.CompareAgeManage());  //15在12和20 之间,所以是True;
}

转载于:https://www.cnblogs.com/Rookieflying/p/10372270.html

你可能感兴趣的文章
dev16 cxgrid 在DLL里报0地址错
查看>>
idea 中解决maven 包冲突的问题(maven helper)
查看>>
Minikube体验
查看>>
[十八]JavaIO之FileReader 和 FileWriter
查看>>
Python 中parse.quote类似JavaScript encodeURI() 函数
查看>>
关于http和rpc的区别(segmentfault上的回答)
查看>>
JIRA简介
查看>>
C语言里的位域
查看>>
XX类库 不包含适合于入口点的静态“Main”方法
查看>>
海量存储(转)
查看>>
图形设备接口的起源
查看>>
区域实现Android实现图片的裁剪(不调用系统功能)
查看>>
Windows下配置Nginx代理Django
查看>>
解决 Delphi XE5 写Android程序的No resource identifier found for attribute... 错误【转】
查看>>
51. N-Queens
查看>>
Linux如何查看JDK的安装路径
查看>>
SyteLine实现字段过滤
查看>>
vs2015启动网站调试提示 HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容。 解决方法...
查看>>
【LeetCode OJ】Longest Substring Without Repeating Characters
查看>>
利用Ant脚本生成war包的详细步骤
查看>>