是否可以从调用栈中反射(reflect)出一个显式的接口(interface)实现?我想使用此信息来查找接口(interface)本身的属性。
给定这段代码:
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)
。
在监 window 口中,如果我查看 method.ToString()
,它会给我 Void InterfaceReflection.IFoo.Test()
(InterfaceReflection 是我的程序集的名称).
我怎样才能从那里到达typeof(IFoo)
?我必须使用程序集本身的基于名称的类型查找,还是 MethodBase
中某处隐藏了一个 Type IFoo
?
更新:
这是最终的解决方案,感谢 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);
}
type
将具有实现方法的接口(interface)类型。这仅适用于显式接口(interface)实现,但这正是我所需要的。现在我可以使用 type
来查询附加到实际接口(interface)类型的属性。
感谢大家的帮助。
最佳答案
使用 VS2010 进行测试,我发现了 DeclaringType,它获取包含该方法的对象类型,您可以从中获取作为 Type 对象的接口(interface)。
public static void Trace() {
var stack = new StackTrace(1, true);
var frame = stack.GetFrame(0);
var method = frame.GetMethod();
var type = method.DeclaringType;
Console.WriteLine(type);
foreach (var i in type.GetInterfaces()) {
Console.WriteLine(i);
}
}
返回:
TestConsole.Foo
TestConsole.IFoo
(我把这个项目叫做TestConsole)
关于c# - 如何从调用栈中反射(reflect)C#显式接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3841282/