【发布时间】:2011-01-31 21:41:34
【问题描述】:
根据 Andrew Hare 的正确答案更新问题:
给定以下 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 - 这是一个人为的例子。我正在开发一个自定义 IoC 自动绑定工具,该工具需要寻找最顶级的接口。我想我会简化这个场景来回答我所追求的根本问题,而不是用 IoC 噪音把它弄得一团糟。另外,现在当其他人需要在不同的上下文中回答这个问题时,IoC 噪音不会妨碍他们。
标签: c# reflection class interface