简体   繁体   中英

Passing a generic type (child of abstract class) to a func

I am writing an application which checks for conditions (ie if a bool is true or false) but it can take any object as a parameter to the func, which derives from HtmlControl.

My func looks like this:

Func<HtmlControl, bool> func

HtmlControl is a base class for all controls in an API, which I use (ArtOfTest WebAII).

I have a class with the following structure:

static class StartTest<T> where T : HtmlControl, new
{

 public static Manager Check (string Url, Func<T, bool> Condition) {}

 public static int Condition(Manager m, string element, Func<T, bool> func, T t) {}
 }

I am using the new constraint because in a collection, there is an error that the type cannot be abstract so when I specify the new constraint, that can only be the concrete, instantiated types.

I want to write something like this:

Method1("Next parameter is a parameter to the func. If I don't write the cast, the   compiler will think its the abstract HtmlControl class, right?", (HtmlImage) img => img.Alt.Length == 0);

However, this errors.

(The stuff in speech marks is part of this question).

When I write the func for a method taking a func as a parameter, how can I pass in a derived type of an abstract class?

The logic is called/consumed from a Windows page codebehind. I make that page generic like so:

  public partial class Window1<T> : Window where T : HtmlControl, new()

But I get an error saying InitializeComponent does not exist in the current context.

(HtmlImage) img => img.Alt.Length == 0

You're trying to cast the whole lambda expression to HtmlImage... If you want to specify the type of the lambda expression parameter, do it like this :

(HtmlImage img) => img.Alt.Length == 0

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