If attribute of the type or its derived types is applied : ParameterInfo « Reflection « C# / C Sharp






If attribute of the type or its derived types is applied

  

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Parameter)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name 
    {
        get 
        {
            return myName;
        }
    }
}

[AttributeUsage(AttributeTargets.Parameter)]
public class MyDerivedAttribute : MyAttribute
{
    public MyDerivedAttribute(string name) : base(name) {}
}

public class MyClass1
{
    public void MyMethod(
        [MyAttribute("This is an example parameter attribute")]
        int i,
        [MyDerivedAttribute("This is another parameter attribute")]
        int j,
        int k )
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes 
{
    public static void Main()
    {
        Type myType = typeof(MyClass1);
        MethodInfo[] myMethods = myType.GetMethods();
        foreach (MethodInfo mi in myMethods)
        {
            ParameterInfo[] myParameters = mi.GetParameters();
            if (myParameters.Length > 0)
            {
                Console.WriteLine(mi);
                foreach (ParameterInfo pi in myParameters)
                {
                    if (pi.IsDefined(typeof(MyAttribute), false))
                    {
                        Console.WriteLine(pi.Position);
                        Console.WriteLine(pi.Name);
                        Console.WriteLine(pi.ParameterType);
                    }
                }
            }
        }  
    }
}

   
    
  








Related examples in the same category

1.ParameterInfo: GetParameters
2.Dumping the methods and their parameters for a class.
3.Dumps the properties names and current values from an object type (used for static classes)
4.Dumps the properties names and current values from an object
5.Gets the attributes for this parameter.
6.Gets all the custom attributes defined on this parameter.
7.Gets a value indicating whether this is an output parameter.
8.Gets the name of the parameter.
9.Gets the Type of this parameter.
10.Append Generic Type parameters to StringBuilder