c#使用lambda检查对象是否属于某种动态类型(通过参数传递)

时间:2017-05-11 02:53:22

标签: c# lambda types

我有一种方法可以检查某个文档是否属于某种类型并选择对其执行某些操作:

 private void OpenOrActivateDocument(Type FormType)
 {    var doc = dmMain.View.Documents.
          Where(x => x.Form is FormType).
          Select(x=>x).First();

          // do something about the found (or not found) doc
 }

这是一个调用上述方法的示例方法:

private void button1_click(Object sender, EventArgs e)
{
        OpenOrActivateDocument(typeof(BudgetExtractionWindow));
}

然而,我在这里得到一个错误:"其中(x => x.Form是FormType)"。如果我要将其更改为特定类型(不通过参数传递),那么我就不会有问题。

1 个答案:

答案 0 :(得分:0)

你应该这样做:

 private void OpenOrActivateDocument(Type FormType)
 {    var doc = dmMain.View.Documents.
          Where(x => x.Form.GetType() == FormType)
          .FirstOrDefault();

      if (doc != null){
          // do something about the found doc
      } else {
          //not found, do some other things
      }    
 }

FormType实际上是一个名为object的{​​{1}}实例,类类型为FormType not 表示任何类名,就像您通常在类实例声明中使用的那样:Type

如果您想检查ClassType instance = new ClassType()是否属于该类型,则应使用对象的方法x.Form

此外,您可以删除GetType子句,因为它将是多余的。

Select是在找不到时返回FirstOrDefault而不是抛出异常。