Access to the value of a Custom Attribute

前端 未结 7 2281
夕颜
夕颜 2021-01-03 20:17

I\'ve got this custom attribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{           


        
相关标签:
7条回答
  • 2021-01-03 20:25

    With my custom attribute:

    [AttributeUsage(AttributeTargets.Method)]
    public class AttributeCustom : Attribute
    {
        public string MyPropertyAttribute { get; private set; }
    
        public AttributeCustom(string myproperty)
        {
            this.MyPropertyAttribute = myproperty;
        }
    }
    

    I create a method for to get attribute with his values:

    public static AttributeCustom GetAttributeCustom<T>(string method) where T : class
    {
        try
        {
            return ((AttributeCustom)typeof(T).GetMethod(method).GetCustomAttributes(typeof(AttributeCustom), false).FirstOrDefault());
        }
        catch(SystemException)
        {
            return null;
        }
    }
    

    With a example class (must be not static because T is generic)

    public class MyClass
    {
        [AttributeCustom("value test attribute")])
        public void MyMethod() 
        {
            //...
        }
    }
    

    Usage:

    var customAttribute = GetAttributeCustom<MyClass>("MyMethod");
    if (customAttribute != null)
    {
        Console.WriteLine(customAttribute.MyPropertyAttribute);
    }
    
    0 讨论(0)
  • 2021-01-03 20:33

    Cast the object to MethodTestingAttibute:

    object actual = method.Invoke(obj, null);
    
    MethodTestingAttibute attribute = (MethodTestingAttibute)method.GetCustomAttributes(typeof(MethodTestAttribute), true)[0];
    string expected = attribute.Value;
    
    bool areEqual = string.Equals(expected, actual != null ? actual.ToString() : null, StringComparison.Ordinal);
    
    0 讨论(0)
  • 2021-01-03 20:35

    To get the value of an attribute property, just cast the object returned by GetCustomAttributes():

    {
        string val;
        object[] atts = method.GetCustomAttributes(typeof(MethodTestAttibute), true);
        if (atts.Length > 0)
           val = (atts[0] as MethodTestingAttibute).Value;
    }
    
    0 讨论(0)
  • 2021-01-03 20:36
    var attribute =
       (MethodTestingAttibute)
       typeof (Vehicles)
          .GetMethod("m1")
          .GetCustomAttributes(typeof (MethodTestingAttibute), false).First();
    Console.WriteLine(attribute.Value);
    
    0 讨论(0)
  • 2021-01-03 20:36

    Please see the following link, it gets the attribute of an enum but you can customize is to get your custom attribute.

    Getting attribute of Enum

    0 讨论(0)
  • 2021-01-03 20:47

    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();
                    }
                }
            }
    
    0 讨论(0)
提交回复
热议问题