Csharp/CSharp Tutorial/Attribute/Attributes Reflection

Материал из .Net Framework эксперт
Версия от 12:14, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Load class method by Attribute

using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class)]
public class ClassTarget : Attribute
{
  public ClassTarget()
  {
  }
}
[AttributeUsage(AttributeTargets.Method )]
public class MethodTarget : Attribute
{
  public MethodTarget()
  {
  }
}
public class MyClass
{
  [MethodTarget]
  public int MyMethod()
  {
    return 5;
  }
}

class MainClass 
{
  public static void Main(string[] args) 
  {
    ClassTarget rs;
    MethodTarget rm;
    Assembly a = Assembly.LoadFrom("MyClass");
    foreach(Type t in a.GetTypes())
    {
      rs = (ClassTarget) Attribute.GetCustomAttribute(t, typeof(ClassTarget));
      if(rs != null)
      {
        foreach(MethodInfo m in t.GetMethods())
        {
          rm = (MethodTarget) Attribute.GetCustomAttribute(m, typeof(MethodTarget));
          if(rm != null)
          {
            Object o = Activator.CreateInstance(t);
            Object[] aa = new Object[0];
            int i = (int) m.Invoke(o, aa);
          }
        }
      }
    }

  }
}

Reflecting on Attributes

//Code revised from 
//A Programmer"s Introduction to C# 2.0, Third Edition
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
public class CodeReviewAttribute: System.Attribute
{
    public CodeReviewAttribute(string reviewer, string date)
    {
        this.reviewer = reviewer;
        this.date = date;
    }
    public string Comment
    {
        get
        {
            return(comment);
        }
        set
        {
            comment = value;
        }
    }
    public string Date
    {
        get
        {
            return(date);
        }
    }
    public string Reviewer
    {
        get
        {
            return(reviewer);
        }
    }
    string reviewer;
    string date;
    string comment;
}
[CodeReview("Name1", "01-12-2000", Comment="comment1")]
[CodeReview("Name2", "01-01-2012", Comment="comment2")]
class Complex
{
}
class MainClass
{
    public static void Main()
    {
        Type type = typeof(Complex);
        foreach (CodeReviewAttribute att in
        type.GetCustomAttributes(typeof(CodeReviewAttribute), false))
        {
            Console.WriteLine("Reviewer: {0}", att.Reviewer);
            Console.WriteLine("Date: {0}", att.Date);
            Console.WriteLine("Comment: {0}", att.rument);
        }
    }
}
Reviewer: Name2
Date: 01-01-2012
Comment: comment2
Reviewer: Name1
Date: 01-12-2000
Comment: comment1

Retrieve Attribute by using reflection

using System;  
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class MyAttribute : Attribute { 
  public string remark; 
 
  public MyAttribute(string comment) { 
    remark = comment; 
  } 
 
  public string Remark { 
    get { 
      return remark; 
    } 
  } 
}  
 
[MyAttribute("This class uses an attribute.")] 
class UseAttrib { 
} 
 
class MainClass {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    Console.Write("Remark: "); 
 
    // Retrieve the MyAttribute. 
    Type tRemAtt = typeof(MyAttribute); 
    MyAttribute ra = (MyAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.WriteLine(ra.remark); 
  }  
}
Attributes in UseAttrib: MyAttribute
Remark: This class uses an attribute.

Use Reflection to get the Attribute

using System;
[assembly:System.CLSCompliantAttribute(true)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class MyDescriptionAttribute : System.Attribute
{
  private string description;
  public string Desc
  {
    get { return description; }
    set { description = value; }
  }
  public MyDescriptionAttribute() {}
  public MyDescriptionAttribute(string desc) 
  { description = desc;}
}

[MyDescriptionAttribute("Info")]
public class MyClass
{
    public MyClass()
    {
    }
}

public class MainClass
{
  public static int Main(string[] args)
  {
    Type t = typeof(MyClass);
  
    // Get all attributes in the assembly.
    object[] customAtts = t.GetCustomAttributes(false);
  
    // List all info.
    Console.WriteLine("Value of MyDescriptionAttribute");
    foreach(MyDescriptionAttribute v in customAtts)
      Console.WriteLine("-> {0}\n", v.Desc);  
    return 0;
  }
}
Value of MyDescriptionAttribute
-> Info

Use the GetCustomAttributes method

using System;
public class TrueFalseAttribute : Attribute
{
  bool bWritten;
  public bool Written()
  {
    return bWritten;
  }
  public TrueFalseAttribute(bool Written)
  {
    bWritten = Written;
  }
}
public class StringAttribute : Attribute
{
  string sStage;
  public string Stage()
  {
    return sStage;
  }
  public StringAttribute(string Stage)
  {
    sStage = Stage;
  }
}
[TrueFalseAttribute(true)]
[StringAttribute("Coding")]
public class Class1
{
}
class MainClass
{
  public static void Main() 
  {
    Console.WriteLine("Class1 attributes: ");object[] aAttributes = Attribute.GetCustomAttributes(typeof(Class1));
    foreach (object attr in aAttributes)
    {
      Console.WriteLine(attr);
    }
  }
}
Class1 attributes:
StringAttribute
TrueFalseAttribute