概述

特性(attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。要设计你自己的自定义特性,无需掌握许多新的概念。 如果你熟悉面向对象的编程,并且知道如何设计类,那么你已经具备大部分所需知识。 自定义特性本质上是直接或间接派生自 system.attribute的传统类。 与传统类一样,自定义特性包含用于存储和检索数据的方法。

实现方式

1、声明自定义特性,一个新的自定义特性应派生自 system.attribute 类。

// 一个自定义特性 bugfix 被赋给类及其成员
[attributeusage(attributetargets.class |
attributetargets.constructor |
attributetargets.field |
attributetargets.method |
attributetargets.property,
allowmultiple = true)]

public class debuginfo : system.attribute

2、构建自定义特性,让我们构建一个名为 debuginfo 的自定义特性,该特性将存储调试程序获得的信息。

// 一个自定义特性 bugfix 被赋给类及其成员
[attributeusage(attributetargets.class |
attributetargets.constructor |
attributetargets.field |
attributetargets.method |
attributetargets.property,
allowmultiple = true)]

public class debuginfo : system.attribute
{
  private int bugno;
  private string developer;
  private string lastreview;
  public string message;

  public debuginfo(int bg, string dev, string d)
{
      this.bugno = bg;
      this.developer = dev;
      this.lastreview = d;
  }

  public int bugno
  {
      get
      {
          return bugno;
      }
  }
  public string developer
  {
      get
      {
          return developer;
      }
  }
  public string lastreview
  {
      get
      {
          return lastreview;
      }
  }
  public string message
  {
      get
      {
          return message;
      }
      set
      {
          message = value;
      }
  }
}

3、应用自定义特性

[debuginfo(45, "zara ali", "12/8/2012", message = "return type mismatch")]
[debuginfo(49, "nuha ali", "10/10/2012", message = "unused variable")]
class rectangle
{
  // 成员变量
  protected double length;
  protected double width;
  public rectangle(double l, double w)
  {
      length = l;
      width = w;
  }
  [debuginfo(55, "zara ali", "19/10/2012",
  message = "return type mismatch")]
  public double getarea()
  {
      return length * width;
  }
  [debuginfo(56, "zara ali", "19/10/2012")]
  public void display()
  {
      console.writeline("length: {0}", length);
      console.writeline("width: {0}", width);
      console.writeline("area: {0}", getarea());
  }
}

以上就是c#如何创建自定义特性的详细内容,更多关于c#创建自定义特性的资料请关注www.887551.com其它相关文章!