zoukankan      html  css  js  c++  java
  • .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     }
  • 相关阅读:
    SharePoint SSS(Security Store Service)服务-PowerShell
    SharePoint BDC(Business Data Connectivity)服务-PowerShell
    win32编辑控件字体
    创建选项卡控件
    利用VkKeyScanA判断大写字母
    使用powershell的remove
    x86和x64下指针的大小
    不使用C库函数(Sprintf)将void* 指针转换为十六进制字符串
    使用pycharm,配置环境
    使用python获得屏幕截图并保存为位图文件
  • 原文地址:https://www.cnblogs.com/blogs2014/p/5527722.html
Copyright © 2011-2022 走看看