ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C#使用自定义特性

C#使用自定义特性

原创 Linux操作系统 作者:iDotNetSpace 时间:2010-10-19 13:33:14 0 删除 编辑

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

 

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

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

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

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

 

测试代码如下:

 

<!--

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

--> 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博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-676262/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765886