2009-06-12 52 views
0

我刚将项目升级到.NET 3.5,并认为我对LINQ有完美的使用。我的应用程序有一个窗口管理器,在运行时跟踪打开的窗口,我试图添加一个FindOpenWindows通用方法。我到目前为止所做的:带有泛型谓词约束的LINQ

List<Form> openWindows; 

    public List<T> FindOpenWindows<T>(Predicate<T> constraint) 
    { 
     var foundTs = from form in openWindows 
          where constraint(form) 
           && form.Created 
          select form; 

     return foundTs as List<T>; 
    } 

但我得到“委托System.Predicate有一些无效的参数。”所以我改写的方法:

public List<T> FindOpenWindows<T>(Predicate<Form> constraint) 
    { 
     var foundTs = from form in openWindows 
          where constraint(form as Form) 
           && form.Created 
          select form; 

     return foundTs as List<T>; 
    } 

我之所以没能进入功能非一般是这样,来电者恰好获得他们要找的窗口类型的列表。

由于我是LINQ和Lambda表达式的新手,我不确定如何在调用FindOpenWindows时为谓词编写代码。我显然需要能够验证被传入的表单不是空的,我需要能够检查它是否与我正在寻找的类型相匹配。

回答

2
public List<T> FindOpenWindows<T>(Predicate<T> constraint) 
    where T : Form 
{ 
    var foundTs = from form in openWindows 
         where constraint(form) 
          && form.Created 
         select form; 

    return foundTs.ToList(); 
} 

试试看。您需要将T约束为Form类型。

+0

谢谢,这完美的作品!我能够弄清楚这个电话应该是: List mainWindows = Program.windowManager.FindOpenWindows ((Form f)=> f is frmMain); – jasonh 2009-06-12 19:45:54