Reputation: 1542
How do I retrieve an attribute from an interface method my class implements?
Edit: I dont know the interface at the time, only the type of the class, or an instance of that class.
Edit: Added the inherited flag to the attribute but it has no effect.
[TestFixture]
public class MyTests {
[Test]
public void shouldGetMyAttribute() {
var type = typeof (MyClass);
var method = type.GetMethod("MyMethod");
var attributes = method.GetCustomAttributes(true);
var myAttribute = attributes.SingleOrDefault(x => x is MyAttributeAttribute);
Assert.That(myAttribute, Is.Not.Null);
}
}
public class MyClass : IMyInterface {
public void MyMethod() {
throw new NotImplementedException();
}
}
public interface IMyInterface {
[MyAttribute]
void MyMethod();
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyAttributeAttribute : Attribute {}
Upvotes: 2
Views: 199
Reputation: 4808
typeof(MyClass).GetInterfaces() will return all interfaces implemented by the class. From there you can use code similar to what Ben M posted to navigate to the right method and attribute.
Upvotes: 2