【问题标题】:How to tell "OfType()" to ignore inherited classes?如何告诉“OfType()”忽略继承的类?
【发布时间】:2018-03-16 15:50:58
【问题描述】:

在我的 WPF 应用程序中,我有以下行:

var windowList = Application.Current.Windows.OfType<Window>().ToList();

这将返回 2 个结果。这些结果有以下几种:

  1. Microsoft.Crm.UnifiedServiceDesk.Desktop
  2. System.Windows.Window

希望返回第二个结果。但是,由于结果 #1 继承了System.Windows.Window,因此它包含在结果中。

有没有办法限制OfType&lt;T&gt;() 函数返回继承的类,还是我必须以其他方式完成?

【问题讨论】:

    标签: c# wpf linq inheritance oftype


    【解决方案1】:

    您不能单独使用 OfType 来实现此目的,但您可以在之后使用 Where 子句:

    var windowList = Application.Current.Windows
        .OfType<Window>()
        .Where(w => w.GetType() == typeof(Window))
        .ToList();
    

    【讨论】:

    • @Sinatr 我刚刚在我的应用程序中使用Application.Current.Windows.Where(w=&gt; w.GetType() == typeof(Window)).ToList(); 尝试了它,我收到错误“表达式评估器中的内部错误”,所以我认为它是。但好消息是,Jon Skeet 的回答非常有效!
    • WindowCollection 是 IEnumerable 但不是通用 IEnumerable。这就是为什么在使用 Where 之前需要使用 OfType。
    • @Sinatr 不可能那么愚蠢。我不知道WindowCollection 不是IEnumerable&lt;T&gt;,现在我知道了!哈哈。我想知道为什么我不能打电话给Application.Current.Windows.ToList()...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2012-03-06
    相关资源
    最近更新 更多