【发布时间】:2011-04-19 23:15:46
【问题描述】:
是否可以从调用堆栈中反映显式接口实现?我想使用这些信息来查找界面本身的属性。
鉴于此代码:
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.???
}
}
具体来说,在 Trace() 中,我希望能够从 method 到达 typeof(IFoo)。
在监视窗口中,如果我查看method.ToString(),它会给我Void InterfaceReflection.IFoo.Test()(InterfaceReflection 是我的程序集的名称)。
我怎样才能从那里到达typeof(IFoo)?我必须使用程序集本身的基于名称的类型查找,还是 Type IFoo 隐藏在 MethodBase 的某处?
更新:
感谢 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 将具有实现方法的接口类型。这仅适用于显式接口实现,但这正是我所需要的。现在我可以使用itype 来查询附加到实际接口类型的属性。
感谢大家的帮助。
【问题讨论】:
标签: c# reflection interface