是否可以從調用堆棧反映顯式接口實現?我想用這個信息來查看接口本身的一個屬性。如何從調用堆棧反思C#顯式接口的實現?
鑑於此代碼:
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.???
}
}
具體而言,在跟蹤(),我希望能夠從method
得到typeof(IFoo)
。
在觀察窗口中,如果我看method.ToString()
它給我Void InterfaceReflection.IFoo.Test()
(InterfaceReflection是我的程序集的名稱)。
如何從那裏到typeof(IFoo)
?我必須從程序集本身使用基於名稱的類型查找,還是有Type IFoo
隱藏在MethodBase
的某處?
UPDATE:
下面是最終的解決方案,這要歸功於凱特
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
來查詢附加到實際接口類型的屬性。
感謝大家的幫助。
啊!就是這樣,謝謝。我只是在看房地產,並沒有考慮看方法。我認爲'GetInterfaces()'是我可以使用的。我將使用'method.Name',它給了我'InterfaceReflection.IFoo.Test',我將取出「IFoo」,並使用'GetInterface()'來找到它的匹配類型。這樣可行。 – scobi 2010-10-01 18:08:05
如果Foo實現了多於一個接口,那麼您仍然必須弄清楚該方法屬於哪一個接口。另外,如果接口中未定義Test,並且是Foo的實際方法,該怎麼辦? – CodingWithSpike 2010-10-01 18:31:41
@ rally25rs:您可以運行i.GetMethods()並與GetFrame(0).GetMethod() – Kyte 2010-10-01 18:48:54