我正在写这行:
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/