我正在编写一个检查条件的应用程序(例如,如果bool为true或false),但它可以将任何对象作为func的参数,该函数派生自HtmlControl。
我的func看起来像这样:
Func<HtmlControl, bool> func
HtmlControl是API中所有控件的基类,我使用它(ArtOfTest WebAII)。
我有一个具有以下结构的类:
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) {}
}
我正在使用新约束,因为在集合中,存在一个错误,该类型不能是抽象的,所以当我指定新约束时,它只能是具体的实例化类型。
我想写这样的东西:
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);
但是,这个错误。
(语音标记中的内容是此问题的一部分)。
当我为一个以func作为参数的方法编写func时,如何传递抽象类的派生类型?
从Windows页面代码隐藏中调用/使用逻辑。我将该页面设为通用的:
public partial class Window1<T> : Window where T : HtmlControl, new()
但是我得到一个错误,说当前上下文中不存在InitializeComponent。
答案 0 :(得分:2)
(HtmlImage)img =&gt; img.Alt.Length == 0
您正在尝试将整个lambda表达式转换为HtmlImage ...如果要指定lambda表达式参数的类型,请执行以下操作:
(HtmlImage img) => img.Alt.Length == 0