简体   繁体   中英

c# using lambda to check if an object is of a certain dynamic type (passed via a parameter)

I have a method that checks if a certain document is of a certain type and chooses to do something about it :

 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
 }

this is a sample method that calls the above method:

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

however, I get an error here : "Where(x => x.Form is FormType)". If I were to change this to a specific type (that is not passed via the parameters), then i would not have a problem.

You should do it this way:

 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
      }    
 }

The FormType is actually an object instance named FormType with class type Type . It does not represent any class name like what you normally use in class instance declaration: ClassType instance = new ClassType() .

If you want to check if your x.Form is of that type, you should use object's method GetType .

Also, you could remove the Select clause as it will be redundant.

FirstOrDefault is to make it return null when not found instead of throwing exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM