Load class method by Attribute : Attributes Reflection : Attribute C# Examples


C# Examples » Attribute » Attributes Reflection »

 

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

                }
            }
        }


    }

}
    
   
  
   




HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Attribute
» Attributes Reflection