I cannot convert this instance in a dictionary
I was writing this line:
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 : IProble开发者_JAVA技巧mFactory<Arithmetic<decimal>>
{ }
And it tells me this error:
Error 1 Cannot implicitly convert type 'Exam.ArithmeticProblemFactory' to 'Exam.IProblemFactory'. An explicit conversion exists (are you missing a cast?)
Error 2 Cannot convert lambda expression to delegate type 'System.Func>' because some of the return types in the block are not implicitly convertible to the delegate return type
What am I doing wrong people?
You need to make your IProblemFactory covariant to support this scenario:
public interface IProblemFactory<out T> where T : IProblem
Basically, this means that T can be an IProblem or anything that implements it in cases like yours.
Here are a couple of articles about Covariance and Contravariance in C#:
- Covariance and Contravariance FAQ
- Covariance and Contravariance in Generics
精彩评论