Is it possible to reflect on an explicit interface implementation from the call stack? I want to use this info to look up an attribute on the interface itself.
Given this code:
interface IFoo
{
void Test();
}
class Foo : IFoo
{
void IFoo.Test() { Program.Trace(); }
}
class Program
{
static void Main(string[] args)
{
IFoo f = new Foo();
f.Test();
}
public static void Trace()
{
var method = new StackTrace(1, false).GetFrame(0).GetMethod();
// method.???
}
}
Specifically, in Trace(), I would like to be able to get to typeof(IFoo)
from method
.
In the watch window, if I look at method.ToString()
it gives me Void InterfaceReflection.IFoo.Test()
(InterfaceReflection is the name of my assembly).
How can I get to typeof(IFoo)
from there? Must I use a name-based type lookup from the assembly itself, or is there a Type IFoo
hidden somewhere in the MethodBase
?
UPDATE:
Here's the final solution, thanks to Kyte
public static void Trace()
{
var method = new StackTrace(1, false).GetFrame(0).GetMethod();
var parts = method.Name.Split('.');
var iname = parts[parts.Length - 2];
var itype = method.DeclaringType.GetInterface(iname);
}
itype
will have the interface type for the implementing method. This will only work with explicit interface implementations, but that's exactly what I need. Now I can use itype
to query attributes attached to the actual interface type.
Thanks to everyone for their help.