C#使用自定義特性

iDotNetSpace發表於2010-10-19

   C#程式設計經常使用屬性,也經常用特性,但是自定義用的比較少,但是老外的程式碼卻很多使用。今天介紹一下,其實很簡單。

 

第一:自定義特性繼承System.Attribute類。

第二:自定特性命名字尾為Attribute,這樣符合微軟的命名風格,也符合編譯器的搜尋規則。

第三:使用[]語法使用自定義特性。

第四:可以使用反射來檢視自定義特性;

 

測試程式碼如下:

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt 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方法中使用反射來檢視,自定義特性的值。

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-676262/,如需轉載,請註明出處,否則將追究法律責任。

相關文章