.NET Attribute 入门【笔记】

 

闲谈:没有系统的学过,偶尔看看,看的也不是很清楚。

     却一直不明白,本来也不难,自己动手写了个示例。结果一目了然……

 

Attribute —— 标记

    可以对方法、类等事务进行附着。增加属性。

 

下面以我见到最多的标记(这里先不说Serializable)使用案例 ——  权限

 

  • 声明一个自己个MyAttribut类——存有字段(Role)、构造函数
  • 自己写一个方法MyAction()(或者类)——给它加上你写的标记,通过构造函数调用,并传参
  • 获取到当前登录的用户类型得到一个值role(例:"1")
  • 获取MyAction()方法的标记attributes
  • 验证:判断当前用户类型值(role)是否等于(或大于)attributes.Role

 

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //获取到标记。
 6             //获取类的标记。typeof(Person).GetCustomAttributes(typeof(MyFirstAttribute), true);
 7             var attributes = typeof(Program).GetMethod("MyAction").GetCustomAttributes(typeof(MyAttribute), true);
 8             MyAttribute myAttribute = attributes[0] as MyAttribute;
 9 
10             Console.WriteLine("如果获取当前用户名=标记,表示可以方法可以访问。");
11             Console.WriteLine("请输入你的用户名等级");
12             string ss = Console.ReadLine();
13 
14             if (ss == myAttribute.Role)
15             {
16                 Console.WriteLine(MyAction());
17             }
18             else
19             {
20                 Console.WriteLine("权限不够。");
21             }
22         }
23         /// <summary>
24         /// 用户类型为1的才可以访问我。
25         /// </summary>
26         /// <returns></returns>
27         [My("1")]
28         public static string MyAction()
29         {
30             return "方法可以访问。";
31         }
32     }
33     /// <summary>
34     /// 自己定义的标记。【权限标记】
35     /// </summary>
36     public class MyAttribute : Attribute
37     {
38         public string Role
39         {
40             get;
41             set;
42         }
43         public MyAttribute(string role)
44         {
45             this.Role = role;
46         }
47     }

 

posted @ 2016-05-25 17:04  淘小人  阅读(1245)  评论(0编辑  收藏  举报