zoukankan      html  css  js  c++  java
  • C#中Attribute介绍

    什么是特性?

      MSDN中定义为:公共语言运行时运行添加类似关键字的描述声明,叫做Attribute,它对程序中的元素进行标注,如类型、方法、字段和属性等。attribute和Microsoft.Net Framework文件的元数据保存在一起,可以用来在运行时描述你的代码,或者在程序运行时影响应用程序的行为

      我们简单地总结:定制特性attribute,本质上是一个类,其为目标元素提供关联附加信息,并在运行时以反射的方式来获取附件信息。

    什么是属性?

      属性是面向对象编程的基本概念,提供了对私有字段的封装,C#中以get和set访问器方法实现对可读可写属性的操作,提供了安全和灵活的数据访问封装。

    特性和属性的区别?

      在功能和应用上,二者其实没什么太多模糊的概念交叉,因此也没有必要放在一起比较。

    attribute通用规则

      1.特性可以应用的目标元素包括:程序集(assemby)、模块(module)、类型(Type)、属性(Property)、事件(Event)、字段(Field)、方法(Method)、参数(param)、返回值(return).

      2.特性以[,]形式展示。放在紧挨着元素上

      3.attribute实例,是在编译期进行初始化,而不是运行期。

      .......

      示例如下:

      

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace _01AttributeTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                Tester t = new Tester();
                t.CannotRun();
    
                Type tp=typeof(Tester);
                MethodInfo mInfo = tp.GetMethod("CannotRun");
                TestAttribute myAtt = (TestAttribute)Attribute.GetCustomAttribute(mInfo, typeof(TestAttribute));
                //myAtt.RunTest();
    
                Console.Read();
            }
    
            
        }
    
        public class Tester
        {
            [Test("Error here.")]
            public  void CannotRun()
            {
    
            }
        }
    
        [AttributeUsage(AttributeTargets.Class | 
            AttributeTargets.Method, 
            Inherited = true)]
        public class TestAttribute : System.Attribute
        {
            public TestAttribute(string message)
            {
                Console.WriteLine(message);
            }
    
            public void RunTest()
            {
                Console.WriteLine("TestAttribute here. ");
            }
        }
    }
    

    参考:

    https://msdn.microsoft.com/zh-cn/library/system.attribute(v=vs.110).aspx

    《你必须知道的.Net》

  • 相关阅读:
    bzoj 1098 [POI2007] 办公楼 biu
    「 Luogu P2574 」 XOR的艺术——线段树
    「 Luogu P2801 」 教主的魔法——分块
    Luogu P1438 无聊的数列
    「 Luogu P2420 」 让我们异或吧
    「 SPOJ GSS3 」 Can you answer these queries III
    「 HDOJ P2227 」 Find the nondecreasing subsequences
    「 HDOJ P3887 」 Counting Offspring
    一些性质及公式
    OI杂记
  • 原文地址:https://www.cnblogs.com/qianxingdewoniu/p/5612465.html
Copyright © 2011-2022 走看看