Load class method by Attribute : Attributes Reflection « Attribute « C# / CSharp Tutorial






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);
          }

        }
      }
    }


  }

}








10.5.Attributes Reflection
10.5.1.Reflecting on Attributes
10.5.2.Retrieve Attribute by using reflection
10.5.3.Use Reflection to get the Attribute
10.5.4.Use the GetCustomAttributes method
10.5.5.Load class method by Attribute