sco*_*obi 5 c# reflection 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.???
}
}
Run Code Online (Sandbox Code Playgroud)
具体而言,在跟踪(),我希望能够去typeof(IFoo)从method.
在观察窗口中,如果我看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);
}
Run Code Online (Sandbox Code Playgroud)
itype将具有实现方法的接口类型.这只适用于显式接口实现,但这正是我需要的.现在我可以itype用来查询附加到实际接口类型的属性.
感谢大家的帮助.
使用 VS2010 进行测试,我发现 DeclaringType,它获取包含该方法的对象类型,从中您可以获取作为 Type 对象的接口。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
返回:
TestConsole.Foo
TestConsole.IFoo
Run Code Online (Sandbox Code Playgroud)
(我将项目命名为TestConsole)
| 归档时间: |
|
| 查看次数: |
2018 次 |
| 最近记录: |