找出(上传的)实例是否未实现特定接口的最佳方法
时间:2020-03-06 14:19:55 来源:igfitidea点击:
也许这样做的必要是"设计异味",但是考虑到另一个问题,我想知道实现此逆的最干净的方法是什么:
foreach(ISomethingable somethingableClass in collectionOfRelatedObjects) { somethingableClass.DoSomething(); }
即如何获取/迭代未实现特定接口的所有对象?
大概我们需要从上至最高级别开始:
foreach(ParentType parentType in collectionOfRelatedObjects) { // TODO: iterate through everything which *doesn't* implement ISomethingable }
通过解决TODO来回答:以最干净/最简单和/或者最有效的方式
解决方案
像这样吗?
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) { } }
这应该可以解决问题:
collectionOfRelatedObjects.Where(o => !(o is ISomethingable))
在LINQ扩展方法OfType <>()的帮助下,我们可以编写:
using System.Linq; ... foreach(ISomethingable s in collection.OfType<ISomethingable>()) { s.DoSomething(); }