特性

1、特性参数
  1、定位参数
  2、命名参数
    命名参数与特性对象的公有字段和属性对应。如果命名参数使用静态的或只读的字段和属性将会产生编译错误

2、特性目标(应用于制定特性要应用的程序元素,它是可选的,不过有时候使用特性目标可以让特性的意图更加明显)
  特性目标分类:
  目标名称        可以应用到
  all           任何元素
  assembly        程序集
  class           类
  constructor      构造函数
  delegate        委托
  enum         枚举
  event         事件
  field          字段
  interface        接口
  method        方法
  module        模块
  param          参数
  property        属性
  return          返回值
  struct          结构

3、创建自定义特性
  1、如果字段和属性要作为特性的命名参数,则特性类的字段和属性必须是公开的,并且属性必须都包含get和set访问器
  2、C#的特性有一个通用的命名约定:给类名添加Attribute后缀,使用特性时,可以省略该后缀

1 using System;
2
3
4  /// <summary>
5 /// Custom Attribute Example
6 /// </summary>
7
8 [
9 Tracker("CR-0001",
10 "some fix",
11 EngineerId = "Joe",
12 ChangeDate = "10/04/2011")
13 ]
14
15 public class SomeProgram
16 {
17 static void Main(string[] args)
18 {
19 SomeProgram sp = new SomeProgram();
20 }
21 }
22
23
24 [
25 AttributeUsage(AttributeTargets.All,
26 AllowMultiple = true,
27 Inherited = true)
28 ]
29
30 class TrackerAttribute : Attribute
31 {
32 public string ProblemId;
33 public string EngineerId;
34
35 private string fixDescription;
36 private DateTime changeDate;
37
38 public string FixDescription
39 {
40 get
41 {
42 return fixDescription;
43 }
44 set
45 {
46 fixDescription = value;
47 }
48 }
49
50 public string ChangeDate
51 {
52 get
53 {
54 return changeDate.ToString("d");
55 }
56 set
57 {
58 changeDate = DateTime.Parse(value);
59 }
60 }
61
62 public TrackerAttribute()
63 {
64 this.ProblemId = "UNASSIGNED";
65 this.EngineerId = "Unidefined Engineer";
66 this.FixDescription = "No description provided";
67 this.ChangeDate = "01/01/2009";
68 }
69
70 public TrackerAttribute(string problemId, string fixDescription)
71 {
72 this.ProblemId = problemId;
73 this.EngineerId = "Unidefined Engineer";
74 this.FixDescription = fixDescription;
75 this.ChangeDate = "01/01/2009";
76 }
77
78 }
posted @ 2011-04-10 12:55  常伟华  阅读(280)  评论(0编辑  收藏  举报