c#編程指南(十八) 使用自訂特性

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.