码迷,mamicode.com
首页 > Windows程序 > 详细

C#你知道我不知道的Attribute

时间:2015-10-08 16:33:32      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

1.   Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。 

2.   特性所提供的信息也称为元数据。 元数据可由应用程序在运行时进行检查以控制程序处理数据的方式,也可以由外部工具在运行前检查以控制应用程序处理或维护自身的方           式。 例如,.NET Framework 预定义特性类型并使用特性类型控制运行时行为,某些编程语言使用特性类型表示 .NET Framework 常规类型系统不直接支持的语言功能。

3.   所有特性类型都直接或间接地从 Attribute 类派生。 特性可应用于任何目标元素;多个特性可应用于同一目标元素;并且特性可由从目标元素派生的元素继承。 使                     用 AttributeTargets 类可以指定特性所应用到的目标元素。目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、       属性、返回值、结构或其他特性。

技术分享

测试代码:

 1   public class Program
 2     {
 3         public static void Main(string[] args)
 4         {
 5             Test t = new Test();
 6             Type type = t.GetType();
 7             foreach (MethodInfo method in type.GetMethods())
 8             {
 9                 foreach (Attribute attr in Attribute.GetCustomAttributes(method))
10                 {
11                     if (attr.GetType() == typeof(SomeAttribute))
12                     {
13                         Console.WriteLine("{0}  have attribute is  {1}", method.Name, ((SomeAttribute)attr).someone);
14                     }
15                 }
16             }
17             Console.Read();
18         }
19     }
20     public class Test
21     {
22         [Some(SomeOne.a)]
23         public void Amethod()
24         { }
25         [Some(SomeOne.b)]
26         public void Bmethod()
27         { }
28         [Some(SomeOne.c)]
29         public void Cmethod()
30         { }
31     }
32     [AttributeUsage(AttributeTargets.All)]
33     public class SomeAttribute : Attribute
34     {
35         
36         public SomeAttribute(SomeOne o)
37         {
38             this.someone = o;
39         }
40         public SomeOne someone { get; set; }
41     }
42     public enum SomeOne
43     {
44         a,
45         b,
46         c
47     }

运行效果:

技术分享

 

C#你知道我不知道的Attribute

标签:

原文地址:http://www.cnblogs.com/JayWist/p/4861226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!