也许这样做的需要是一种“设计味道”,但考虑另一个问题,我想知道实现这个的最干净的方法是什么 这个的:

foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
  somethingableClass.DoSomething();
}

IE。如何获取/迭代所有对象 实现特定的接口?

想必您需要首先升级到最高级别:

foreach(ParentType parentType in collectionOfRelatedObjects)
{
  // TODO: iterate through everything which *doesn't* implement ISomethingable 
} 

通过解决 TODO 来回答:以最干净/最简单和/或最有效的方式

有帮助吗?

解决方案

这应该可以解决问题:

collectionOfRelatedObjects.Where(o => !(o is ISomethingable))

其他提示

像这样的东西吗?

foreach (ParentType parentType in collectionOfRelatedObjects) {
    if (!(parentType is ISomethingable)) {
    }
}

也许最好是一路走下去并改进变量名称:

foreach (object obj in collectionOfRelatedObjects)
{
    if (obj is ISomethingable) continue;

    //do something to/with the not-ISomethingable
}

J D OConal 是执行此操作的最佳方法,但作为旁注,您可以使用 as 关键字来转换对象,如果它不是该类型,它将返回 null。

所以像这样:

foreach (ParentType parentType in collectionOfRelatedObjects) {
    var obj = (parentType as ISomethingable);
    if (obj == null)  {
    }
}

在 LINQ 扩展方法 OfType<>() 的帮助下,您可以编写:

using System.Linq;

...

foreach(ISomethingable s in collection.OfType<ISomethingable>())
{
  s.DoSomething();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top