找出(upcast)实例是否未实现特定接口的最佳方法

Gor*_*ley 1 .net c# interface

也许需要这样做是一种"设计气味",但想到另一个问题,我想知道实现这个逆转的最简洁方法是什么:

foreach(ISomethingable somethingableClass in collectionOfRelatedObjects)
{
  somethingableClass.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

即如何获取/遍历所有实现特定接口的对象?

大概你需要从向上升到最高级别开始:

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

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

J D*_*nal 6

像这样的东西?

foreach (ParentType parentType in collectionOfRelatedObjects) {
    if (!(parentType is ISomethingable)) {
    }
}
Run Code Online (Sandbox Code Playgroud)