确认IEnumerable <interface1>中的对象类型也实现了Interface2 </interface1>

时间:2015-03-24 16:49:09

标签: c# interface casting resharper

我有一个接口ICoordinate和两种实现它的类型。我有一个IEnumerable<ICoordinate>的集合。实现ICoordinate的其中一种类型也实现了接口IExpirable

对象一

  • ICoordinate
  • IExpirable

对象

  • ICoordinate

IEnumerable<ICoordinate>由每种类型的对象组成。我希望能够确定每个对象是否实现IExpirable,因为我已经知道这两个对象都实现了ICoordinate。我尝试使用以下方式进行检查:

var coordObj = coord as IExpirable

if(coord is IExpirable)

这两个例子都让resharper抱怨suspicious comparisons or and suspicious casts。具体来说,他们说there is no type in the solution which is inherited from both type A and type B

2 个答案:

答案 0 :(得分:0)

我使用GetInterface方法。

AppSession.Current.ModulesConfiguration.Select(
                    module =>
                    {
                        var path = Path.Combine(Path.Combine(pathToAssemblies, module.ModuleRelativePathForDll),
                            module.BusinessModuleDllName);
                        return path;
                    })
                    .Select(Assembly.LoadFrom)
                    .SelectMany(a => a.GetTypes())
                    .FirstOrDefault(type => type.GetInterface(interfaceType.Name) != null);

答案 1 :(得分:0)

您可以遍历您的集合并选择所有实现Linq的第二个接口(或者更好的扩展方法,而不是真正的LINQ语法):

using System.Linq;
using System.Collections.Generic;

        IEnumerable<ICoordinate> list=...;
        foreach(IExpirable expirable in list.OfType<IExpirable>())
        {
            ...
        }