c#编程指南(十八) 使用自定义特性

C#编程经常使用属性,也经常用特性,但是自定义用的比较少,但是老外的代码却很多使用。今天介绍一下,其实很简单。

 

第一:自定义特性继承System.Attribute类。

第二:自定特性命名后缀为Attribute,这样符合微软的命名风格,也符合编译器的搜索规则。

第三:使用[]语法使用自定义特性。

第四:可以使用反射来查看自定义特性;

 

测试代码如下:

 

1 using System;
2  using System.Collections.Generic;
3  using System.Text;
4  using System.Reflection;
5
6  namespace MyAttribute
7 {
8 [Extra("This is an example attribute.")]
9 public class TestClass
10 {
11 public string Temp { get; set; }
12 }
13
14
15 class Program
16 {
17 static void Main(string[] args)
18 {
19 Object[] attrs = typeof(TestClass).GetCustomAttributes(true);
20 foreach (Object o in attrs)
21 {
22 if (o is ExtraAttribute)
23 {
24 Console.WriteLine((o as ExtraAttribute).Extra);
25 }
26 }
27 }
28
29 }
30
31
32 [AttributeUsage(AttributeTargets.Class)]
33 public class ExtraAttribute : Attribute
34 {
35 private string _extra;
36 public ExtraAttribute(string extra)
37 {
38 _extra = extra;
39 }
40 public string Extra { get { return _extra; } }
41 }
42
43 }

 

解释:我定义了一个ExtraAttribute的自定义特性,然后在TestClass类使用,在main方法中使用反射来查看,自定义特性的值。

 

posted @ 2010-10-18 14:53  香山飘雪  阅读(1741)  评论(0编辑  收藏  举报