我有一种方法可以检查某个文档是否属于某种类型并选择对其进行处理:
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));
}
但是,我在这里遇到错误:“Where(x => x.Form is FormType)”。如果我将其更改为特定类型(不是通过参数传递的),那么我就不会有问题。
最佳答案
你应该这样做:
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
实际上是一个名为FormType
的对象
实例,类类型为Type
。它不代表您通常在类实例声明中使用的任何类名:ClassType instance = new ClassType()
。
如果你想检查你的x.Form
是否是那种类型,你应该使用对象的方法GetType
。
另外,您可以删除 Select
子句,因为它是多余的。
FirstOrDefault
是让它在没有找到时返回null
,而不是抛出异常。
关于c# 使用 lambda 检查对象是否属于某种动态类型(通过参数传递),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905738/