C# 无法分配操作<;tDelivedThing>;采取行动<;伊辛>;
我有以下类定义:C# 无法分配操作<;tDelivedThing>;采取行动<;伊辛>;,c#,C#,我有以下类定义: public class Registry { private List<Action<IThing>> _thingActions = new List<Action<IThing>>(); public Register<TDerivedThing>(Action<TDerivedThing> thingAction) where TDerivedThing :
public class Registry
{
private List<Action<IThing>> _thingActions = new List<Action<IThing>>();
public Register<TDerivedThing>(Action<TDerivedThing> thingAction)
where TDerivedThing : IThing
{
// this line causes compilation issue
_thingActions.Add(thingAction);
}
}
公共类注册表
{
私有列表_thingActions=新列表();
公众登记册(行动事项行动)
我在哪儿
{
//这一行导致编译问题
_thingActions.Add(thingAction);
}
}
为什么这会抱怨它不能将操作
分配给操作
,我应该如何解决这个问题?如果C允许您这样做,这样的代码是有效的:
interface IFruit {
void Eat();
}
class Apple : IFruit {
// ...
void EatApple();
}
class Pear : IFruit {
// ...
void EatPear();
}
void EatApple(Apple a) {
a.EatApple();
}
void EatPear(Pear p) {
p.EatPear();
}
Action<IFruit> fruitAction = EatApple;
fruitAction(new Pear()); // Calls EatApple(new Pear())
接口IFruit{
空吃();
}
苹果类:IFruit{
// ...
无效吃苹果();
}
梨类:IFruit{
// ...
void EatPear();
}
苹果(苹果a){
a、 吃苹果();
}
梨(梨p){
p、 EatPear();
}
行动果果行动=吃苹果;
果味(新梨());//调用EatApple(新的Pear())
演员阵容是无效的,因为它不应该是,你不应该尝试这样做的第一位。你的列表包含操作所有必须是接受任何结果的操作。当然不是,列表
也不能分配给列表
,即使EventArgs是一个对象
public void Register<TDerivedThing>(Action<TDerivedThing> thingAction)
where TDerivedThing : IThing
{
_thingActions.Add(t => thingAction(t as TDerivedThing));
}
公共无效登记簿(Action thingAction)
我在哪儿
{
_添加(t=>thingAction(t作为TDerivedThing));
}
可能是一个解决方案,但我不知道您的应用程序。这是一个协方差和方差问题。我建议你读一下这方面的文章。它对您的问题有完整的答案。您不能,这不是类型安全的。愚蠢的问题。TDerivedThing是否实现了接口?这是一个协方差限制。请看这里:大概您将在一些IThing
上迭代内容操作
?当你的信息
不是TDerivedThing
时会发生什么?@StianStandahl它确实是。。。where应该表示这就是我为什么发布它的原因!;-)