I have a interface that defines some methods with attributes. These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface. What am I missing?
public class SomeClass: ISomeInterface { MyAttribute GetAttribute() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true); if (attributes.Count() == 0) throw new Exception('could not find MyAttribute defined for ' + methodBase.Name); return attributes[0] as MyAttribute; } void DoSomething() { MyAttribute ma = GetAttribute(); string s = ma.SomeProperty; } }
The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method ‘Foo’ can implement an interface method ‘Bar’. To do this, you would need to investigate the interface map: