更新問題給出安德魯野兔的正確答案:如何列舉在繼承類上直接定義的接口列表?
下面的C#類:
public class Bar : Foo, IDisposable
{
// implementation of Bar and IDisposable
}
public class Foo : IEnumerable<int>
{
// implementation of Foo and all its inherited interfaces
}
我想這樣不就斷言失敗(注意以下的方法:你可以不改變斷言):
public void SomeMethod()
{
// This doesn't work
Type[] interfaces = typeof(Bar).GetInterfaces();
Debug.Assert(interfaces != null);
Debug.Assert(interfaces.Length == 1);
Debug.Assert(interfaces[0] == typeof(IDisposable));
}
能
別人的幫助,通過固定此方法,以便斷言不失敗?
調用typeof(Bar).GetInterfaces()
不起作用,因爲它返回的整個界面的層次結構(即interfaces
變量包含IEnumerable<int>
,IEnumerable
和IDisposable
),而不僅僅是頂層。
爲什麼你會這樣做?如果斷言Bar實現了IDisposable,會不會更好更乾淨呢? – Svish 2010-03-25 21:09:54
@Svish - 這是一個人爲的例子。我正在開發一個自定義的IoC自動綁定工具,它需要查找最頂級的接口。我想我會簡化場景來回答我之前的根本問題,而不是把它與IoC噪音混淆起來。另外,現在當別人需要在不同背景下回答這個問題時,IoC噪音不會妨礙他們。 – Jordan 2010-03-26 13:43:59