Csharp/CSharp Tutorial/Attribute/Attribute

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Assembly-Level Attributes

<source lang="csharp">Attribute Meaning in Life AssemblyCompanyAttribute basic company information AssemblyCopyrightAttribute any copyright information AssemblyCultureAttribute information on cultures or languages AssemblyDescriptionAttribute a description of the product AssemblyKeyFileAttribute the name of the file containing the key pair AssemblyOperatingSystemAttribute operating system AssemblyProcessorAttribute processors to support AssemblyProductAttribute Provides product information AssemblyTrademarkAttribute Provides trademark information AssemblyVersionAttribute assembly"s version information, in the format <major.minor.build.revision></source>

Custom Attributes

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

   [AttributeUsage(AttributeTargets.Class |
                   AttributeTargets.Constructor |
                   AttributeTargets.Field |
                   AttributeTargets.Method |
                   AttributeTargets.Property,
                   AllowMultiple = true)]
   public class BugFixAttribute : System.Attribute
   {
       public int      BugID;
       public string   Date;
       public string   Programmer;
       public string   Comment;
       public BugFixAttribute(int bugID,string programmer,string date){
           this.BugID = bugID;
           this.Programmer = programmer;
           this.Date = date;
       }
   }
   [BugFixAttribute(1, "B", "01/04/05",Comment = "value")]
   public class MyMath
   {
       public double DoFunc1(double param1)
       {
           return param1 + DoFunc2(param1);
       }
       public double DoFunc2(double param1)
       {
           return param1 / 3;
       }
   }</source>

Providing an Attribute Constructor

<source lang="csharp">using System; public class CommandLineSwitchAliasAttribute : Attribute {

  public CommandLineSwitchAliasAttribute(string alias)
  {
      Alias = alias;
  }
  public string Alias
  {
     get { return _Alias; }
     set { _Alias = value; }
 }
 private string _Alias;

} class CommandLineInfo {

 [CommandLineSwitchAliasAttribute("?")]
 public bool Help
 {
     get { return _Help; }
     set { _Help = value; }
 }
 private bool _Help;

}</source>

Retrieving a Specific Attribute and Checking Its Initialization

<source lang="csharp">using System; using System.Reflection; public class CommandLineSwitchAliasAttribute : Attribute {

   public CommandLineSwitchAliasAttribute(string alias)
   {
       Alias = alias;
   }
   public string Alias
   {
       get { return _Alias; }
       set { _Alias = value; }
   }
   private string _Alias;

} class CommandLineInfo {

   [CommandLineSwitchAliasAttribute("?")]
   public bool Help
   {
       get { return _Help; }
       set { _Help = value; }
   }
   private bool _Help;

}

class MainClass {

   static void Main()
   {
       PropertyInfo property = typeof(CommandLineInfo).GetProperty("Help");
       CommandLineSwitchAliasAttribute attribute = (CommandLineSwitchAliasAttribute)property.GetCustomAttributes(typeof(CommandLineSwitchAliasAttribute), false)[0];
       if (attribute.Alias == "?")
       {
           Console.WriteLine("Help(?)");
       };
   }

}</source>

Saving a Document Using System.SerializableAttribute

<source lang="csharp">using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; class Program {

 public static void Main()
 {
     Stream stream;
     Document documentBefore = new Document();
     documentBefore.Title ="test";
     Document documentAfter;
     using (stream = File.Open(documentBefore.Title + ".bin", FileMode.Create))
     {
         BinaryFormatter formatter = new BinaryFormatter();
         formatter.Serialize(stream, documentBefore);
     }
     using (stream = File.Open(documentBefore.Title + ".bin", FileMode.Open))
     {
         BinaryFormatter formatter = new BinaryFormatter();
         documentAfter = (Document)formatter.Deserialize(stream);
     }
     Console.WriteLine(documentAfter.Title);
 }

} [Serializable] class Document {

 public string Title = null;
 public string Data = null;
 [NonSerialized]
 public long _WindowHandle = 0;
 class Image
 {
 }
 [NonSerialized]
                           private Image Picture = new Image();

}</source>

Use Attributes to mark a method

You can add declarative information to a program by using an attribute.

An attribute defines additional information that is associated with a class, structure, method, and so on.

  1. An attribute is supported by a class that inherits System.Attribute.
  2. All attribute classes must be subclasses of System.Attribute.
  3. This built-in attribute AttributeUsage specifies the types of items to which the attribute can be applied.


<source lang="csharp">using System.Diagnostics;

class MainClass {

   [Conditional("DEBUG")]
   public void Validate()
   {
   }

}</source>

C# defines three built-in attributes:

  1. AttributeUsage,
  2. Conditional,
  3. Obsolete.