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方法中使用反射來查看,自訂特性的值。