协方差、委托和泛型类型约束

本文关键字:泛型类型 约束 方差 | 更新日期: 2023-09-27 18:31:26

public void Foo<T>(Func<T> bar)
 where T: IMyInterface
{
   Func<IMyInterface> func = bar;
}

我已经有一段时间没有理解协方差了,但这不应该编译吗?

任何bar可以返回的东西也是一种IMyInterface。似乎有什么问题?

协方差、委托和泛型类型约束

这是 C# 4 中的协方差错误吗?

正确的代码是:

public void Foo<T>(Func<T> bar)
 where T: class, IMyInterface
{
   Func<IMyInterface> func = bar;
}