Alex Rivera | Logout

Access to the value of a Custom Attribute

Asked 2011-06-30T17:00:21.933
30

I've got this custom attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{   
    public string Value{ get; private set; }
    public MethodTestingAttibute (string value)
    {
        this.Value= value;

    }
}

To be used like this:

[MethodTestingAttibute("2")]
public int m1() {return 3; }

And my difficulty is to take the value of "2" of MethodTestingAttibute

object result = method.Invoke(obj, new Type[] {}); // here i get the return

Now I want to compare this result to the value of MethodTestingAttibute. How can I do that? I'm trying to go up to this road but without success:

method.GetCustomAttributes(typeof(MethodTestAttibute), true)[0]...

What is the proper way to get access to the field of the custom attribute?

Edit
Report

1 Answer

0

Check the code here http://msdn.microsoft.com/en-us/library/bfwhbey7.aspx

Excerpt:

        // Get the AClass type to access its metadata.
        Type clsType = typeof(AClass);
        // Get the type information for Win32CallMethod.
        MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
        if (mInfo != null)
        {
            // Iterate through all the attributes of the method.
            foreach(Attribute attr in
                Attribute.GetCustomAttributes(mInfo)) {
                // Check for the Obsolete attribute.
                if (attr.GetType() == typeof(ObsoleteAttribute))
                {
                    Console.WriteLine("Method {0} is obsolete. " +
                        "The message is:",
                        mInfo.Name);
                    Console.WriteLine("  \"{0}\"",
                        ((ObsoleteAttribute)attr).Message);
                }

                // Check for the Unmanaged attribute.
                else if (attr.GetType() == typeof(UnmanagedAttribute))
                {
                    Console.WriteLine(
                        "This method calls unmanaged code.");
                    Console.WriteLine(
                        String.Format("The Unmanaged attribute type is {0}.",
                                      ((UnmanagedAttribute)attr).Win32Type));
                    AClass myCls = new AClass();
                    myCls.Win32CallMethod();
                }
            }
        }
answered 2011-06-30T17:06:02.033

Your Answer