[英]c# using lambda to check if an object is of a certain dynamic type (passed via a parameter)
我有一種方法來檢查某個文檔是否屬於某種類型,並選擇對其進行處理:
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
的object
實例,其類類型為Type
。 它不代表任何類名稱,比如你在正常類實例聲明中使用: ClassType instance = new ClassType()
如果要檢查x.Form
是否屬於該類型,則應使用對象的方法GetType
。
另外,您可以刪除Select
子句,因為它將是多余的。
FirstOrDefault
將使它在找不到時返回null
而不是FirstOrDefault
異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.