如何添加Func使用该约束类型将受约束的 T 存储到集合中
我正在尝试创建一个函数列表,但我很挣扎。这是一个简化版本:
public class ValueGetter
{
public List<Func<Control, string>> Operations { get; set; }
public ValueGetter()
{
this.Operations = new List<Func<Control, string>>();
}
public void Map<T>(Func<T, string> valueGetter) where T : Control
{
this.Operations.Add(valueGetter);
}
}
当我尝试将函数添加到集合中时,问题就出现了。我本来可以做到这一点,因为 T 是一个控件,但这无法编译。
有什么方法可以将函数添加到这个集合中吗?
I'm trying to create a list of Functions but I'm struggling. Here is a simplified version:
public class ValueGetter
{
public List<Func<Control, string>> Operations { get; set; }
public ValueGetter()
{
this.Operations = new List<Func<Control, string>>();
}
public void Map<T>(Func<T, string> valueGetter) where T : Control
{
this.Operations.Add(valueGetter);
}
}
The issue comes when I try to add the function to the collection. I would have through I'd be able to do this as T is a control however this doesn't compile.
Is there a way I can add the function to this collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是不可能的。
虽然
T
是一个Control
,但并非所有Control
都是T
。如果将
Func
添加到列表中,然后使用Button< 调用它(作为
Func
),会发生什么情况/代码>?您可以使用协方差来转换
Func;
到Func;其中 T : Control>
,因为任何可能的T
也是Control
。That's not possible.
Although
T
is aControl
, not allControl
s areT
s.What happens if you add a
Func<TextBox, bool>
to the list, then call it (as aFunc<Control, string>
) with aButton
?You can use covariance to cast a
Func<Control, string>
to aFunc<T, string> where T : Control>
, because any possibleT
is also aControl
.您应该将该类声明为通用类:
You shoud declare the class as generic:
这是行不通的,因为您最终会在列表中包含一个
Func
,但您最终可能会使用一个Label 来调用它
。该函数需要一个Button
,并希望与Label
一起使用?您可以执行以下操作:
换句话说,为每个 Control 类型设置单独的
ValueGetter
。编辑:另一个想法:您可以添加一个仅在类型正确时才允许操作的函数,例如:
在这种情况下,如果
Button
期望函数是给定一个Label
,它只会返回 null。This wouldn’t work, because you would end up having, for example, a
Func<Button, string>
in your list, but you could end up calling it with, say, aLabel
. What is the function, which expects aButton
, expected to do with aLabel
?You could do something like this:
In other words, have separate
ValueGetter
s for each Control type.Edit: Another idea: You could add a function that simply allows the operation only if the type is right, for example:
In this case, if the
Button
-expecting function is given aLabel
, it would simply return null.