11

Whats the best approach for getting the attribute values from a classes methods and from the interface methods when the methods are overloaded?

For example I would want to know that in the following example the Get method with one parameter has the two attributes and the values are 5 and "any" while the other method has attributes with values 7 and "private".

public class ScopeAttribute : System.Attribute
{
    public string Allowed { get; set; }    
}

public class SizeAttribute : System.Attribute
{
    public int Max { get; set; }
}

public interface Interface1
{
    [SizeAttribute( Max = 5 )]
    string Get( string name );

    [SizeAttribute( Max = 7 )]
    string Get( string name, string area );

}

public class Class1 : Interface1
{
    [ScopeAttribute( Allowed = "any" )]
    public string Get( string name )
    {
        return string.Empty;
    }

    [ScopeAttribute( Allowed = "private" )]
    public string Get( string name, string area )
    {
        return string.Empty;
    }
}
Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
Phil Carson
  • 884
  • 8
  • 18

3 Answers3

7

The only way I found was to check what interfaces the class implements and check attributes of the properties (if any exist) on those interfaces:

static bool HasAttribute (PropertyInfo property, string attribute) {
  if (property == null)
    return false;

  if (GetCustomAttributes ().Any (a => a.GetType ().Name == attribute))
    return true;

  var interfaces = property.DeclaringType.GetInterfaces ();

  for (int i = 0; i < interfaces.Length; i++)
    if (HasAttribute (interfaces[i].GetProperty (property.Name), attribute))
      return true;

  return false;
}

You can probably adopt it to methods equally easy.


Note: overall approach is tested but the code itself is ad-hoc and may not compile.

Hazel へいぜる
  • 2,751
  • 1
  • 12
  • 44
1

You can use TypeDescriptor API

System.ComponentModel.TypeDescriptor.GetAttributes(object)
Peyman
  • 3,068
  • 1
  • 18
  • 32
  • 3
    Won't this mean that I have to instantiate the class first? And will this provide the objects attributes rather than the objects methods attributes? – Phil Carson Jun 19 '11 at 22:05
  • The linked doc states, that this method has an overload and you can provide a type as well, e.g. GetAttributes(typeof(MyClass)), however it doesn't seem to return attributes from interface properties at all – infografnet May 11 '23 at 18:42
0

You should use reflection to get the custom attributes values

use MemberInfo.GetCustomAttributes Method to return the custom attributes attached to your member

here is a tutorial http://msdn.microsoft.com/en-us/library/aa288454(v=VS.71).aspx

EDIT: for get attributes from interface look at here

Community
  • 1
  • 1
Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
  • It is not enough here. With this method you can get `ScopeAttribute` from the example. For implemented interface and `SizeAttribute` it is not enough. – Ivan Danilov Jun 17 '11 at 01:51