【问题标题】:Confirming type of object in IEnumerable<Interface1> also implements Interface2确认 IEnumerable<Interface1> 中的对象类型也实现了 Interface2
【发布时间】:2015-03-24 16:49:09
【问题描述】:

我有一个接口ICoordinate 和两种实现它的类型。我收藏了IEnumerable&lt;ICoordinate&gt;。实现ICoordinate的类型之一也实现了接口IExpirable

对象一

  • ICoordinate
  • IExpirable

对象二

  • ICoordinate

IEnumerable&lt;ICoordinate&gt; 由许多每种类型的对象组成。我希望能够确定每个对象是否实现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

【问题讨论】:

  • 如何将对象转换为其底层类型,然后测试它是否实现了 IExpirable?这显然是一种处理接口的丑陋方式,但也许这可以解决 reshaper 的投诉?
  • 看起来应该可以了,你能发布更多代码让我们看到完整的上下文吗?
  • 悠悠说的话。当我尝试时,最小的复制不会从 R# 中得到任何抱怨。请提供给出问题的最小代码。只是一件小事:当你说“。我有一个IEnumerable&lt;ICoordinate&gt; 的集合”时,你的意思是你有很多 IEnumerable&lt;ICoordinate&gt;s 或一个 IEnumerable&lt;ICoordinate&gt;(这当然是一个集合)?如果是前者,那么是的,没有必要尝试将每个 IEnumerable&lt;ICoordinate&gt; 依次转换为 IExpirable...

标签: c# interface casting resharper


【解决方案1】:

我使用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);

【讨论】:

    【解决方案2】:

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

    using System.Linq;
    using System.Collections.Generic;
    
            IEnumerable<ICoordinate> list=...;
            foreach(IExpirable expirable in list.OfType<IExpirable>())
            {
                ...
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多