c# - 我无法在字典中转换此实例

标签 c# oop interface

我正在写这行:

var factory = new Dictionary<Types, Func<IProblemFactory<IProblem>>>();
        factory.Add(Types.Arithmetic, ()=> new ArithmeticProblemFactory()));

public interface IProblem { ... }
public interface IProblemFactory<T> where T : IProblem
{
    // Some stuff
}

public class Arithmetic<TResult> : IProblem
{ }
public class ArithmeticProblemFactory : IProblemFactory<Arithmetic<decimal>>
{ }

它告诉我这个错误:

错误 1 ​​无法将类型“Exam.ArithmeticProblemFactory”隐式转换为“Exam.IProblemFactory”。存在显式转换(您是否缺少强制转换?)

错误 2 无法将 lambda 表达式转换为委托(delegate)类型“System.Func>”,因为 block 中的某些返回类型无法隐式转换为委托(delegate)返回类型

我做错了什么吗?

最佳答案

您需要使 IProblemFactory 具有协变才能支持此场景:

public interface IProblemFactory<out T> where T : IProblem

基本上,这意味着 T 可以是 IProblem 或在像您这样的情况下实现它的任何东西。

这里有几篇关于 C# 中的协方差和逆变的文章:

关于c# - 我无法在字典中转换此实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7183622/

相关文章:

Java,处理对象权限

c# - 以编程方式比较两种方法的 IL

c# - Xamarin.Forms 缓存图像

c# - 在 C# 中重置 IronScheme 引擎

python - 为什么在 Python 中在类已经定义之后添加属性并不违法?

php - 当我的抽象类实现接口(interface)时,我应该创建抽象方法吗?

java - 最小化 Golang 中的接口(interface)

c# - 如何使用 PLINQ 进行延迟加载?

c++ - 为什么在接口(interface)中定义私有(private)成员/方法?

c++ - 复制构造函数被调用了多少次?